Artificial Intelligence Nanodegree

Convolutional Neural Networks

Project: Write an Algorithm for a Dog Identification App


Solution by Carsten Isert, Sept. 2017

In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.

The rubric contains optional "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this IPython notebook.


Why We're Here

In this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!).

Sample Dog Output

In this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!

The Road Ahead

We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.

  • Step 0: Import Datasets
  • Step 1: Detect Humans
  • Step 2: Detect Dogs
  • Step 3: Create a CNN to Classify Dog Breeds (from Scratch)
  • Step 4: Use a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 6: Write your Algorithm
  • Step 7: Test Your Algorithm

Step 0: Import Datasets

Import Dog Dataset

In the code cell below, we import a dataset of dog images. We populate a few variables through the use of the load_files function from the scikit-learn library:

  • train_files, valid_files, test_files - numpy arrays containing file paths to images
  • train_targets, valid_targets, test_targets - numpy arrays containing onehot-encoded classification labels
  • dog_names - list of string-valued dog breed names for translating labels
In [1]:
from sklearn.datasets import load_files       
from keras.utils import np_utils
import numpy as np
from glob import glob

# define function to load train, test, and validation datasets
def load_dataset(path):
    data = load_files(path)
    dog_files = np.array(data['filenames'])
    dog_targets = np_utils.to_categorical(np.array(data['target']), 133)
    return dog_files, dog_targets

# load train, test, and validation datasets
train_files, train_targets = load_dataset('dogImages/train')
valid_files, valid_targets = load_dataset('dogImages/valid')
test_files, test_targets = load_dataset('dogImages/test')

# load list of dog names
dog_names = [item[20:-1] for item in sorted(glob("dogImages/train/*/"))]

# print statistics about the dataset
print('There are %d total dog categories.' % len(dog_names))
print('There are %s total dog images.\n' % len(np.hstack([train_files, valid_files, test_files])))
print('There are %d training dog images.' % len(train_files))
print('There are %d validation dog images.' % len(valid_files))
print('There are %d test dog images.'% len(test_files))
Using TensorFlow backend.
There are 133 total dog categories.
There are 8351 total dog images.

There are 6680 training dog images.
There are 835 validation dog images.
There are 836 test dog images.

Import Human Dataset

In the code cell below, we import a dataset of human images, where the file paths are stored in the numpy array human_files.

In [2]:
import random
random.seed(8675309)

# load filenames in shuffled human dataset
human_files = np.array(glob("lfw/*/*"))
random.shuffle(human_files)

# print statistics about the dataset
print('There are %d total human images.' % len(human_files))
There are 13233 total human images.

Step 1: Detect Humans

We use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images. OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the haarcascades directory.

In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.

In [66]:
import cv2                
import matplotlib.pyplot as plt                        
%matplotlib inline                               

# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')

# load color (BGR) image
img = cv2.imread(human_files[3])
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# find faces in image
faces = face_cascade.detectMultiScale(gray)

# print number of faces detected in the image
print('Number of faces detected:', len(faces))

# get bounding box for each detected face
for (x,y,w,h) in faces:
    # add bounding box to color image
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.show()
Number of faces detected: 3

Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale function executes the classifier stored in face_cascade and takes the grayscale image as a parameter.

In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.

Write a Human Face Detector

We can use this procedure to write a function that returns True if a human face is detected in an image and False otherwise. This function, aptly named face_detector, takes a string-valued file path to an image as input and appears in the code block below.

In [67]:
# returns "True" if face is detected in image stored at img_path
def face_detector(img_path):
    img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray)
    return len(faces) > 0

(IMPLEMENTATION) Assess the Human Face Detector

Question 1: Use the code cell below to test the performance of the face_detector function.

  • What percentage of the first 100 images in human_files have a detected human face?
  • What percentage of the first 100 images in dog_files have a detected human face?

Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short and dog_files_short.

Answer: The performance on the human dataset is acceptable, but for the dogs it is quite bad with 11%.

  • Percentage of detected faces in human dataset: 0.98 - 0.99
  • Percentage of detected faces in dog dataset: 0.11
In [68]:
human_files_short = human_files[:100]
dog_files_short = train_files[:100]
# Do NOT modify the code above this line.

number_of_detected_faces = 0
for file in human_files_short:
    if face_detector(file):
        number_of_detected_faces += 1
        
percentage_of_detected_faces = number_of_detected_faces / 100
print("Percentage of detected faces in human dataset: ", percentage_of_detected_faces)

number_of_detected_faces = 0
for file in dog_files_short:
    if face_detector(file):
        number_of_detected_faces += 1
        
percentage_of_detected_faces = number_of_detected_faces / 100
print("Percentage of detected faces in dog dataset: ", percentage_of_detected_faces)
Percentage of detected faces in human dataset:  0.99
Percentage of detected faces in dog dataset:  0.11

Question 2: This algorithmic choice necessitates that we communicate to the user that we accept human images only when they provide a clear view of a face (otherwise, we risk having unneccessarily frustrated users!). In your opinion, is this a reasonable expectation to pose on the user? If not, can you think of a way to detect humans in images that does not necessitate an image with a clearly presented face?

Answer: If we design the UI in a way that clearly communicates this to the user, I think this is a totally reasonable design choice. We are talking about a fun app anyway and people are of course free to also try this with photos of their cats or horses or cars and find out what dog breed they resemble. This might just be rubbish, but it also might be a lot of fun.

One approach to solve this, is to make a too stage approach. The first stage will try to find the location of faces in an image and the corresponding bounding box, and the second stage will take this area and do the analysis. This approach has been used e.g. at Baidu to make a face detection framework for allowing employees to enter restricted areas based on their face id.

We suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :). Please use the code cell below to design and test your own face detection algorithm. If you decide to pursue this optional task, report performance on each of the datasets.

In [40]:
## (Optional) TODO: Report the performance of another  
## face detection algorithm on the LFW dataset
### Feel free to use as many code cells as needed.

# Ideas for later: 
# 1. Use the dog and human datasets to train a CNN that can distinguish between the humans and the dogs for this specific dataset.
# 2. Look for some existing algorithms that can be used (in TF or Keras). A first search didn't show anything promising.

Step 2: Detect Dogs

In this section, we use a pre-trained ResNet-50 model to detect dogs in images. Our first line of code downloads the ResNet-50 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories. Given an image, this pre-trained ResNet-50 model returns a prediction (derived from the available categories in ImageNet) for the object that is contained in the image.

In [69]:
from keras.applications.resnet50 import ResNet50

# define ResNet50 model
ResNet50_model = ResNet50(weights='imagenet')

Pre-process the Data

When using TensorFlow as backend, Keras CNNs require a 4D array (which we'll also refer to as a 4D tensor) as input, with shape

$$ (\text{nb_samples}, \text{rows}, \text{columns}, \text{channels}), $$

where nb_samples corresponds to the total number of images (or samples), and rows, columns, and channels correspond to the number of rows, columns, and channels for each image, respectively.

The path_to_tensor function below takes a string-valued file path to a color image as input and returns a 4D tensor suitable for supplying to a Keras CNN. The function first loads the image and resizes it to a square image that is $224 \times 224$ pixels. Next, the image is converted to an array, which is then resized to a 4D tensor. In this case, since we are working with color images, each image has three channels. Likewise, since we are processing a single image (or sample), the returned tensor will always have shape

$$ (1, 224, 224, 3). $$

The paths_to_tensor function takes a numpy array of string-valued image paths as input and returns a 4D tensor with shape

$$ (\text{nb_samples}, 224, 224, 3). $$

Here, nb_samples is the number of samples, or number of images, in the supplied array of image paths. It is best to think of nb_samples as the number of 3D tensors (where each 3D tensor corresponds to a different image) in your dataset!

In [70]:
from keras.preprocessing import image                  
from tqdm import tqdm

# Note: modified these to functions, so that we can later also read the inception tensors which 
# have a different format 
def path_to_tensor(img_path, width=224, height=224):
    # loads RGB image as PIL.Image.Image type
    img = image.load_img(img_path, target_size=(width, height))
    # convert PIL.Image.Image type to 3D tensor with shape (width, heigth, 3)
    x = image.img_to_array(img)
    # convert 3D tensor to 4D tensor with shape (1, width, height, 3) and return 4D tensor
    return np.expand_dims(x, axis=0)

def paths_to_tensor(img_paths, width=224, height=224):
    list_of_tensors = [path_to_tensor(img_path, width, height) for img_path in tqdm(img_paths)]
    return np.vstack(list_of_tensors)

Making Predictions with ResNet-50

Getting the 4D tensor ready for ResNet-50, and for any other pre-trained model in Keras, requires some additional processing. First, the RGB image is converted to BGR by reordering the channels. All pre-trained models have the additional normalization step that the mean pixel (expressed in RGB as $[103.939, 116.779, 123.68]$ and calculated from all pixels in all images in ImageNet) must be subtracted from every pixel in each image. This is implemented in the imported function preprocess_input. If you're curious, you can check the code for preprocess_input here.

Now that we have a way to format our image for supplying to ResNet-50, we are now ready to use the model to extract the predictions. This is accomplished with the predict method, which returns an array whose $i$-th entry is the model's predicted probability that the image belongs to the $i$-th ImageNet category. This is implemented in the ResNet50_predict_labels function below.

By taking the argmax of the predicted probability vector, we obtain an integer corresponding to the model's predicted object class, which we can identify with an object category through the use of this dictionary.

In [71]:
from keras.applications.resnet50 import preprocess_input, decode_predictions

def ResNet50_predict_labels(img_path):
    # returns prediction vector for image located at img_path
    img = preprocess_input(path_to_tensor(img_path))
    return np.argmax(ResNet50_model.predict(img))

Write a Dog Detector

While looking at the dictionary, you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from 'Chihuahua' to 'Mexican hairless'. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained ResNet-50 model, we need only check if the ResNet50_predict_labels function above returns a value between 151 and 268 (inclusive).

We use these ideas to complete the dog_detector function below, which returns True if a dog is detected in an image (and False if not).

In [72]:
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
    prediction = ResNet50_predict_labels(img_path)
    return ((prediction <= 268) & (prediction >= 151)) 

(IMPLEMENTATION) Assess the Dog Detector

Question 3: Use the code cell below to test the performance of your dog_detector function.

  • What percentage of the images in human_files_short have a detected dog?
  • What percentage of the images in dog_files_short have a detected dog?

Answer:

  • Percentage of detected dogs in human dataset: 0.00 - 0.01
  • Percentage of detected dogs in dog dataset: 1.0
In [73]:
number_of_detected_dogs = 0
for file in human_files_short:
    if dog_detector(file):
        number_of_detected_dogs += 1
        
percentage_of_detected_dogs = number_of_detected_dogs / 100
print("Percentage of detected dogs in human dataset: ", percentage_of_detected_dogs)

number_of_detected_dogs = 0
for file in dog_files_short:
    if dog_detector(file):
        number_of_detected_dogs += 1
        
percentage_of_detected_dogs = number_of_detected_dogs / 100
print("Percentage of detected dogs in dog dataset: ", percentage_of_detected_dogs)
Percentage of detected dogs in human dataset:  0.0
Percentage of detected dogs in dog dataset:  1.0

Step 3: Create a CNN to Classify Dog Breeds (from Scratch)

Now that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN from scratch (so, you can't use transfer learning yet!), and you must attain a test accuracy of at least 1%. In Step 5 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.

Be careful with adding too many trainable layers! More parameters means longer training, which means you are more likely to need a GPU to accelerate the training process. Thankfully, Keras provides a handy estimate of the time that each epoch is likely to take; you can extrapolate this estimate to figure out how long it will take for your algorithm to train.

We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have great difficulty in distinguishing between a Brittany and a Welsh Springer Spaniel.

Brittany Welsh Springer Spaniel

It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).

Curly-Coated Retriever American Water Spaniel

Likewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.

Yellow Labrador Chocolate Labrador Black Labrador

We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imbalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.

Remember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!

Pre-process the Data

We rescale the images by dividing every pixel in every image by 255.

In [9]:
from PIL import ImageFile                            
ImageFile.LOAD_TRUNCATED_IMAGES = True                 

# pre-process the data for Keras
train_tensors = paths_to_tensor(train_files).astype('float32')/255
valid_tensors = paths_to_tensor(valid_files).astype('float32')/255
test_tensors = paths_to_tensor(test_files).astype('float32')/255
100%|██████████| 6680/6680 [00:53<00:00, 125.10it/s]
100%|██████████| 835/835 [00:05<00:00, 141.02it/s]
100%|██████████| 836/836 [00:05<00:00, 141.67it/s]

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    model.summary()

We have imported some Python modules to get you started, but feel free to import as many modules as you need. If you end up getting stuck, here's a hint that specifies a model that trains relatively fast on CPU and attains >1% test accuracy in 5 epochs:

Sample CNN

Question 4: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. If you chose to use the hinted architecture above, describe why you think that CNN architecture should work well for the image classification task.

Answer: My approach was to use the model from the cifar-10 classification as a baseline. Once I checked the number of parameters it was very huge. This was due to the size of the images being 224 x 224 instead of 32 x 32. So I reduced the number of parameters to enable faster training and avoid overfitting by increasing the sizes of the max pooling layers from 2 to 6. This helps to reduce the size of the layers and therefore the number of parameters. I also reduced the number of filters to 16 and 32 again to reduce the number of parameters. The dropouts were kept. The final step was to massively reduce the nodes in the last fully connected layer. I took a hint from the architecture above. It probably makes sense to have at least one neuron representing one dog breed. So I chose the number of nodes to 133. Additionally, I changed the optimizer to Adam, as in my experience, Adam works better as RMSProp, as it combines the methods from Momentum and RMSProp. The test accuracy after 10 epochs was 6.1005%. The validation accuracy in the last step was around 6.8% or even higher. That means that we might already be in some state of overfitting, but it is hard to tell at this stage. Later on, I had run the whole notebook and loaded the weihgts, but I had to run it again, so this way, I ran an additional 10 epochs and reached a accuracy of 10.6459%, so overfitting was not so severe at all. As I exceeded the requirements of 1% by far and training takes a lot of time, I didn't push much further. But I think there is a lot of room for improvement, which of course is shown in the later exercises.

I also compared my results to the excellent notebook from Jay Madhava at https://github.com/madhavajay/nd889/blob/master/2_deep_learning/1_dog_breed_classifier/dog_app.ipynb and found out that my network performs better without data augmentation. So I did not work further on this.

In [74]:
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential

model = Sequential()

model.add(Conv2D(filters=16, kernel_size=3, padding='same', activation='relu', 
                        input_shape=(224, 224, 3)))
model.add(Conv2D(filters=16, kernel_size=3, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=6))
model.add(Dropout(0.25))

model.add(Conv2D(filters=32, kernel_size=3, padding='same', activation='relu'))
model.add(Conv2D(filters=32, kernel_size=3, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=6))
model.add(Dropout(0.3))

model.add(Flatten())

model.add(Dense(133, activation='relu'))
model.add(Dropout(0.5))

model.add(Dense(133, activation='softmax'))

model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_193 (Conv2D)          (None, 224, 224, 16)      448       
_________________________________________________________________
conv2d_194 (Conv2D)          (None, 224, 224, 16)      2320      
_________________________________________________________________
max_pooling2d_46 (MaxPooling (None, 37, 37, 16)        0         
_________________________________________________________________
dropout_4 (Dropout)          (None, 37, 37, 16)        0         
_________________________________________________________________
conv2d_195 (Conv2D)          (None, 37, 37, 32)        4640      
_________________________________________________________________
conv2d_196 (Conv2D)          (None, 37, 37, 32)        9248      
_________________________________________________________________
max_pooling2d_47 (MaxPooling (None, 6, 6, 32)          0         
_________________________________________________________________
dropout_5 (Dropout)          (None, 6, 6, 32)          0         
_________________________________________________________________
flatten_4 (Flatten)          (None, 1152)              0         
_________________________________________________________________
dense_12 (Dense)             (None, 133)               153349    
_________________________________________________________________
dropout_6 (Dropout)          (None, 133)               0         
_________________________________________________________________
dense_13 (Dense)             (None, 133)               17822     
=================================================================
Total params: 187,827
Trainable params: 187,827
Non-trainable params: 0
_________________________________________________________________

Compile the Model

In [75]:
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [76]:
# helpers for training CNNs taken from 
# https://github.com/madhavajay/nd889/blob/master/2_deep_learning/1_dog_breed_classifier/dog_app.ipynb
# many thanks to Jay for these helper functions

import keras
import timeit

# graph the history of model.fit
def show_history_graph(history):
    # summarize history for accuracy
    plt.plot(history.history['acc'])
    plt.plot(history.history['val_acc'])
    plt.title('model accuracy')
    plt.ylabel('accuracy')
    plt.xlabel('epoch')
    plt.legend(['train', 'validation'], loc='upper left')
    plt.show()
    # summarize history for loss
    plt.plot(history.history['loss'])
    plt.plot(history.history['val_loss'])
    plt.title('model loss')
    plt.ylabel('loss')
    plt.xlabel('epoch')
    plt.legend(['train', 'validation'], loc='upper left')
    plt.show() 

# callback to show the total time taken during training and for each epoch
class EpochTimer(keras.callbacks.Callback):
    train_start = 0
    train_end = 0
    epoch_start = 0
    epoch_end = 0
    
    def get_time(self):
        return timeit.default_timer()

    def on_train_begin(self, logs={}):
        self.train_start = self.get_time()
 
    def on_train_end(self, logs={}):
        self.train_end = self.get_time()
        print('Training took {} seconds'.format(self.train_end - self.train_start))
 
    def on_epoch_begin(self, epoch, logs={}):
        self.epoch_start = self.get_time()
 
    def on_epoch_end(self, epoch, logs={}):
        self.epoch_end = self.get_time()
        print('Epoch {} took {} seconds'.format(epoch, self.epoch_end - self.epoch_start))
In [77]:
from keras.callbacks import ModelCheckpoint  

epochs = 10
epochtimer = EpochTimer()

### Do NOT modify the code below this line.

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.from_scratch.hdf5', 
                               verbose=1, save_best_only=True)

hist = model.fit(train_tensors, train_targets, 
              validation_data=(valid_tensors, valid_targets),
              epochs=epochs, batch_size=20, callbacks=[checkpointer, epochtimer], verbose=1)

show_history_graph(hist)
Train on 6680 samples, validate on 835 samples
Epoch 1/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.8878 - acc: 0.0083Epoch 00000: val_loss improved from inf to 4.88112, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 0 took 50.76989618099833 seconds
6680/6680 [==============================] - 50s - loss: 4.8878 - acc: 0.0082 - val_loss: 4.8811 - val_acc: 0.0144
Epoch 2/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.8764 - acc: 0.0095Epoch 00001: val_loss improved from 4.88112 to 4.86941, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 1 took 34.45688237200011 seconds
6680/6680 [==============================] - 34s - loss: 4.8765 - acc: 0.0094 - val_loss: 4.8694 - val_acc: 0.0096
Epoch 3/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.8338 - acc: 0.0149Epoch 00002: val_loss improved from 4.86941 to 4.75944, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 2 took 34.3747872290005 seconds
6680/6680 [==============================] - 34s - loss: 4.8335 - acc: 0.0148 - val_loss: 4.7594 - val_acc: 0.0240
Epoch 4/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.7244 - acc: 0.0239- ETA: 1s - loss: 4.Epoch 00003: val_loss improved from 4.75944 to 4.64157, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 3 took 34.51418420199843 seconds
6680/6680 [==============================] - 34s - loss: 4.7243 - acc: 0.0240 - val_loss: 4.6416 - val_acc: 0.0311
Epoch 5/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.6208 - acc: 0.0266Epoch 00004: val_loss improved from 4.64157 to 4.57508, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 4 took 34.3969490519994 seconds
6680/6680 [==============================] - 34s - loss: 4.6207 - acc: 0.0265 - val_loss: 4.5751 - val_acc: 0.0347
Epoch 6/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.5402 - acc: 0.0330Epoch 00005: val_loss improved from 4.57508 to 4.48511, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 5 took 34.42016799599878 seconds
6680/6680 [==============================] - 34s - loss: 4.5403 - acc: 0.0331 - val_loss: 4.4851 - val_acc: 0.0455
Epoch 7/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.4617 - acc: 0.0410Epoch 00006: val_loss improved from 4.48511 to 4.43388, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 6 took 34.4062093370012 seconds
6680/6680 [==============================] - 34s - loss: 4.4614 - acc: 0.0410 - val_loss: 4.4339 - val_acc: 0.0515
Epoch 8/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.3746 - acc: 0.0419Epoch 00007: val_loss improved from 4.43388 to 4.31523, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 7 took 34.4013791039979 seconds
6680/6680 [==============================] - 34s - loss: 4.3752 - acc: 0.0419 - val_loss: 4.3152 - val_acc: 0.0575
Epoch 9/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.2927 - acc: 0.0548Epoch 00008: val_loss improved from 4.31523 to 4.23245, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 8 took 34.40714438500072 seconds
6680/6680 [==============================] - 34s - loss: 4.2924 - acc: 0.0546 - val_loss: 4.2324 - val_acc: 0.0647
Epoch 10/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.2074 - acc: 0.0634Epoch 00009: val_loss improved from 4.23245 to 4.22158, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 9 took 34.42035932199724 seconds
6680/6680 [==============================] - 34s - loss: 4.2060 - acc: 0.0635 - val_loss: 4.2216 - val_acc: 0.0611
Training took 360.58184475500093 seconds

Load the Model with the Best Validation Loss

In [50]:
model.load_weights('saved_models/weights.best.from_scratch.hdf5')

Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 1%.

In [51]:
# get index of predicted dog breed for each image in test set
dog_breed_predictions = [np.argmax(model.predict(np.expand_dims(tensor, axis=0))) for tensor in test_tensors]

# report test accuracy
test_accuracy = 100*np.sum(np.array(dog_breed_predictions)==np.argmax(test_targets, axis=1))/len(dog_breed_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 10.6459%

Step 4: Use a CNN to Classify Dog Breeds

To reduce training time without sacrificing accuracy, we show you how to train a CNN using transfer learning. In the following step, you will get a chance to use transfer learning to train your own CNN.

Obtain Bottleneck Features

In [52]:
bottleneck_features = np.load('bottleneck_features/DogVGG16Data.npz')
train_VGG16 = bottleneck_features['train']
valid_VGG16 = bottleneck_features['valid']
test_VGG16 = bottleneck_features['test']

Model Architecture

The model uses the the pre-trained VGG-16 model as a fixed feature extractor, where the last convolutional output of VGG-16 is fed as input to our model. We only add a global average pooling layer and a fully connected layer, where the latter contains one node for each dog category and is equipped with a softmax.

In [53]:
VGG16_model = Sequential()
VGG16_model.add(GlobalAveragePooling2D(input_shape=train_VGG16.shape[1:]))
VGG16_model.add(Dense(133, activation='softmax'))

VGG16_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_3 ( (None, 512)               0         
_________________________________________________________________
dense_7 (Dense)              (None, 133)               68229     
=================================================================
Total params: 68,229
Trainable params: 68,229
Non-trainable params: 0
_________________________________________________________________

Compile the Model

In [54]:
VGG16_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

Train the Model

In [55]:
epochtimer = EpochTimer()

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.VGG16.hdf5', 
                               verbose=1, save_best_only=True)

hist = VGG16_model.fit(train_VGG16, train_targets, 
              validation_data=(valid_VGG16, valid_targets),
              epochs=20, batch_size=20, callbacks=[checkpointer, epochtimer], verbose=1)

show_history_graph(hist)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6660/6680 [============================>.] - ETA: 0s - loss: 12.6215 - acc: 0.1119Epoch 00000: val_loss improved from inf to 11.21869, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 19s - loss: 12.6224 - acc: 0.1121 - val_loss: 11.2187 - val_acc: 0.1916
Epoch 2/20
6600/6680 [============================>.] - ETA: 0s - loss: 10.6202 - acc: 0.2629Epoch 00001: val_loss improved from 11.21869 to 10.66728, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 5s - loss: 10.6155 - acc: 0.2636 - val_loss: 10.6673 - val_acc: 0.2623
Epoch 3/20
6620/6680 [============================>.] - ETA: 0s - loss: 10.2118 - acc: 0.3139Epoch 00002: val_loss improved from 10.66728 to 10.52781, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 5s - loss: 10.2156 - acc: 0.3135 - val_loss: 10.5278 - val_acc: 0.2802
Epoch 4/20
6600/6680 [============================>.] - ETA: 0s - loss: 10.0674 - acc: 0.3420Epoch 00003: val_loss did not improve
6680/6680 [==============================] - 5s - loss: 10.0605 - acc: 0.3422 - val_loss: 10.5381 - val_acc: 0.2886
Epoch 5/20
6620/6680 [============================>.] - ETA: 0s - loss: 9.9841 - acc: 0.3576Epoch 00004: val_loss improved from 10.52781 to 10.45448, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 5s - loss: 9.9815 - acc: 0.3578 - val_loss: 10.4545 - val_acc: 0.2910
Epoch 6/20
6640/6680 [============================>.] - ETA: 0s - loss: 9.9269 - acc: 0.3663Epoch 00005: val_loss improved from 10.45448 to 10.40803, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 5s - loss: 9.9334 - acc: 0.3659 - val_loss: 10.4080 - val_acc: 0.2994
Epoch 7/20
6600/6680 [============================>.] - ETA: 0s - loss: 9.8835 - acc: 0.3739Epoch 00006: val_loss improved from 10.40803 to 10.34101, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 5s - loss: 9.8986 - acc: 0.3731 - val_loss: 10.3410 - val_acc: 0.3102
Epoch 8/20
6600/6680 [============================>.] - ETA: 0s - loss: 9.7899 - acc: 0.3765Epoch 00007: val_loss improved from 10.34101 to 10.23656, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 5s - loss: 9.7827 - acc: 0.3769 - val_loss: 10.2366 - val_acc: 0.3102
Epoch 9/20
6640/6680 [============================>.] - ETA: 0s - loss: 9.6278 - acc: 0.3864Epoch 00008: val_loss improved from 10.23656 to 9.95909, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 5s - loss: 9.6130 - acc: 0.3873 - val_loss: 9.9591 - val_acc: 0.3174
Epoch 10/20
6620/6680 [============================>.] - ETA: 0s - loss: 9.4266 - acc: 0.4011Epoch 00009: val_loss improved from 9.95909 to 9.86261, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 5s - loss: 9.4204 - acc: 0.4013 - val_loss: 9.8626 - val_acc: 0.3329
Epoch 11/20
6640/6680 [============================>.] - ETA: 0s - loss: 9.1542 - acc: 0.4084Epoch 00010: val_loss improved from 9.86261 to 9.58777, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 5s - loss: 9.1449 - acc: 0.4090 - val_loss: 9.5878 - val_acc: 0.3329
Epoch 12/20
6600/6680 [============================>.] - ETA: 0s - loss: 8.9103 - acc: 0.4302Epoch 00011: val_loss improved from 9.58777 to 9.40255, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 5s - loss: 8.9071 - acc: 0.4302 - val_loss: 9.4026 - val_acc: 0.3521
Epoch 13/20
6600/6680 [============================>.] - ETA: 0s - loss: 8.7462 - acc: 0.4400Epoch 00012: val_loss improved from 9.40255 to 9.33868, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 5s - loss: 8.7459 - acc: 0.4400 - val_loss: 9.3387 - val_acc: 0.3569
Epoch 14/20
6640/6680 [============================>.] - ETA: 0s - loss: 8.6294 - acc: 0.4526Epoch 00013: val_loss improved from 9.33868 to 9.20304, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 5s - loss: 8.6411 - acc: 0.4516 - val_loss: 9.2030 - val_acc: 0.3677
Epoch 15/20
6640/6680 [============================>.] - ETA: 0s - loss: 8.5398 - acc: 0.4610Epoch 00014: val_loss improved from 9.20304 to 9.10512, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 5s - loss: 8.5273 - acc: 0.4618 - val_loss: 9.1051 - val_acc: 0.3760
Epoch 16/20
6580/6680 [============================>.] - ETA: 0s - loss: 8.4850 - acc: 0.4631Epoch 00015: val_loss did not improve
6680/6680 [==============================] - 4s - loss: 8.4914 - acc: 0.4626 - val_loss: 9.1237 - val_acc: 0.3641
Epoch 17/20
6660/6680 [============================>.] - ETA: 0s - loss: 8.3301 - acc: 0.4649Epoch 00016: val_loss improved from 9.10512 to 9.05872, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 5s - loss: 8.3317 - acc: 0.4648 - val_loss: 9.0587 - val_acc: 0.3749
Epoch 18/20
6600/6680 [============================>.] - ETA: 0s - loss: 8.2690 - acc: 0.4747Epoch 00017: val_loss improved from 9.05872 to 8.96935, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 5s - loss: 8.2635 - acc: 0.4751 - val_loss: 8.9693 - val_acc: 0.3665
Epoch 19/20
6660/6680 [============================>.] - ETA: 0s - loss: 8.1023 - acc: 0.4842Epoch 00018: val_loss improved from 8.96935 to 8.74283, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 4s - loss: 8.0973 - acc: 0.4846 - val_loss: 8.7428 - val_acc: 0.3904
Epoch 20/20
6620/6680 [============================>.] - ETA: 0s - loss: 7.9837 - acc: 0.4932Epoch 00019: val_loss did not improve
6680/6680 [==============================] - 5s - loss: 7.9748 - acc: 0.4939 - val_loss: 8.7497 - val_acc: 0.3916
Out[55]:
<keras.callbacks.History at 0x7ff7bd161e48>

Load the Model with the Best Validation Loss

In [56]:
VGG16_model.load_weights('saved_models/weights.best.VGG16.hdf5')

Test the Model

Now, we can use the CNN to test how well it identifies breed within our test dataset of dog images. We print the test accuracy below.

In [57]:
# get index of predicted dog breed for each image in test set
VGG16_predictions = [np.argmax(VGG16_model.predict(np.expand_dims(feature, axis=0))) for feature in test_VGG16]

# report test accuracy
test_accuracy = 100*np.sum(np.array(VGG16_predictions)==np.argmax(test_targets, axis=1))/len(VGG16_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 40.7895%

Predict Dog Breed with the Model

In [58]:
from extract_bottleneck_features import *

def VGG16_predict_breed(img_path):
    # extract bottleneck features
    bottleneck_feature = extract_VGG16(path_to_tensor(img_path))
    # obtain predicted vector
    predicted_vector = VGG16_model.predict(bottleneck_feature)
    # return dog breed that is predicted by the model
    return dog_names[np.argmax(predicted_vector)]

Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)

You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.

In Step 4, we used transfer learning to create a CNN using VGG-16 bottleneck features. In this section, you must use the bottleneck features from a different pre-trained model. To make things easier for you, we have pre-computed the features for all of the networks that are currently available in Keras:

The files are encoded as such:

Dog{network}Data.npz

where {network}, in the above filename, can be one of VGG19, Resnet50, InceptionV3, or Xception. Pick one of the above architectures, download the corresponding bottleneck features, and store the downloaded file in the bottleneck_features/ folder in the repository.

(IMPLEMENTATION) Obtain Bottleneck Features

In the code block below, extract the bottleneck features corresponding to the train, test, and validation sets by running the following:

bottleneck_features = np.load('bottleneck_features/Dog{network}Data.npz')
train_{network} = bottleneck_features['train']
valid_{network} = bottleneck_features['valid']
test_{network} = bottleneck_features['test']
In [78]:
resnet_bottleneck_features = np.load('bottleneck_features/DogResnet50Data.npz')
train_resnet50 = resnet_bottleneck_features['train']
valid_resnet50 = resnet_bottleneck_features['valid']
test_resnet50 = resnet_bottleneck_features['test']

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    <your model's name>.summary()

Question 5: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.

Answer: I basically just did copy and paste from the VGG16 model, but renamed everything to Resnet50. This resulted in a performance / accuracy of 83.4928%, which far exceeds the requirements. It was interesting to observe that the model converged quite early (epoch 11) and then overfitted severely. This suggests to use additional methods to reduce this overfitting with dropouts, data augmentation as the dataset is quite small and a more complex model at the end, maybe with several fully conneted layers resembling the original structure of ResNet.

Some of these experiments were done (see section 8 for results and comments).

During these experiements, I also checked out to change the batch size to 64 and got test accuracy of 84.6890%. However, these results are not consistent, in the last run, the accuracy for these settings were only 82.7751%.

In [79]:
Resnet50_model = Sequential()
Resnet50_model.add(GlobalAveragePooling2D(input_shape=train_resnet50.shape[1:]))
Resnet50_model.add(Dense(133, activation='softmax'))

Resnet50_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_8 ( (None, 2048)              0         
_________________________________________________________________
dense_14 (Dense)             (None, 133)               272517    
=================================================================
Total params: 272,517
Trainable params: 272,517
Non-trainable params: 0
_________________________________________________________________

(IMPLEMENTATION) Compile the Model

In [80]:
Resnet50_model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [17]:
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.RESNET50.hdf5', 
                               verbose=1, save_best_only=True)
epochtimer = EpochTimer()

hist = Resnet50_model.fit(train_resnet50, train_targets, 
              validation_data=(valid_resnet50, valid_targets),
              epochs=20, batch_size=64, callbacks=[checkpointer, epochtimer], verbose=1)

show_history_graph(hist)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6400/6680 [===========================>..] - ETA: 0s - loss: 2.2010 - acc: 0.5078Epoch 00000: val_loss improved from inf to 0.99110, saving model to saved_models/weights.best.RESNET50.hdf5
Epoch 0 took 0.8444056329999512 seconds
6680/6680 [==============================] - 0s - loss: 2.1488 - acc: 0.5178 - val_loss: 0.9911 - val_acc: 0.7198
Epoch 2/20
6400/6680 [===========================>..] - ETA: 0s - loss: 0.5343 - acc: 0.8778Epoch 00001: val_loss improved from 0.99110 to 0.73953, saving model to saved_models/weights.best.RESNET50.hdf5
Epoch 1 took 0.5568292850002763 seconds
6680/6680 [==============================] - 0s - loss: 0.5323 - acc: 0.8775 - val_loss: 0.7395 - val_acc: 0.7772
Epoch 3/20
6336/6680 [===========================>..] - ETA: 0s - loss: 0.2966 - acc: 0.9426Epoch 00002: val_loss improved from 0.73953 to 0.64846, saving model to saved_models/weights.best.RESNET50.hdf5
Epoch 2 took 0.5595133810002153 seconds
6680/6680 [==============================] - 0s - loss: 0.2924 - acc: 0.9442 - val_loss: 0.6485 - val_acc: 0.8060
Epoch 4/20
6336/6680 [===========================>..] - ETA: 0s - loss: 0.1802 - acc: 0.9771Epoch 00003: val_loss improved from 0.64846 to 0.60313, saving model to saved_models/weights.best.RESNET50.hdf5
Epoch 3 took 0.5621653090001928 seconds
6680/6680 [==============================] - 0s - loss: 0.1793 - acc: 0.9774 - val_loss: 0.6031 - val_acc: 0.8144
Epoch 5/20
6336/6680 [===========================>..] - ETA: 0s - loss: 0.1197 - acc: 0.9913Epoch 00004: val_loss improved from 0.60313 to 0.59576, saving model to saved_models/weights.best.RESNET50.hdf5
Epoch 4 took 0.558907008999995 seconds
6680/6680 [==============================] - 0s - loss: 0.1199 - acc: 0.9910 - val_loss: 0.5958 - val_acc: 0.8168
Epoch 6/20
6400/6680 [===========================>..] - ETA: 0s - loss: 0.0873 - acc: 0.9948Epoch 00005: val_loss improved from 0.59576 to 0.57995, saving model to saved_models/weights.best.RESNET50.hdf5
Epoch 5 took 0.5616246929994304 seconds
6680/6680 [==============================] - 0s - loss: 0.0876 - acc: 0.9946 - val_loss: 0.5799 - val_acc: 0.8251
Epoch 7/20
6336/6680 [===========================>..] - ETA: 0s - loss: 0.0665 - acc: 0.9973Epoch 00006: val_loss improved from 0.57995 to 0.57417, saving model to saved_models/weights.best.RESNET50.hdf5
Epoch 6 took 0.5604336850001346 seconds
6680/6680 [==============================] - 0s - loss: 0.0663 - acc: 0.9973 - val_loss: 0.5742 - val_acc: 0.8287
Epoch 8/20
6336/6680 [===========================>..] - ETA: 0s - loss: 0.0542 - acc: 0.9972Epoch 00007: val_loss improved from 0.57417 to 0.56189, saving model to saved_models/weights.best.RESNET50.hdf5
Epoch 7 took 0.561673547999817 seconds
6680/6680 [==============================] - 0s - loss: 0.0539 - acc: 0.9973 - val_loss: 0.5619 - val_acc: 0.8287
Epoch 9/20
6400/6680 [===========================>..] - ETA: 0s - loss: 0.0434 - acc: 0.9981Epoch 00008: val_loss improved from 0.56189 to 0.55318, saving model to saved_models/weights.best.RESNET50.hdf5
Epoch 8 took 0.5601561049998054 seconds
6680/6680 [==============================] - 0s - loss: 0.0435 - acc: 0.9982 - val_loss: 0.5532 - val_acc: 0.8287
Epoch 10/20
6400/6680 [===========================>..] - ETA: 0s - loss: 0.0371 - acc: 0.9981Epoch 00009: val_loss did not improve
Epoch 9 took 0.5450695930003349 seconds
6680/6680 [==============================] - 0s - loss: 0.0372 - acc: 0.9982 - val_loss: 0.5555 - val_acc: 0.8287
Epoch 11/20
6400/6680 [===========================>..] - ETA: 0s - loss: 0.0324 - acc: 0.9984Epoch 00010: val_loss improved from 0.55318 to 0.55092, saving model to saved_models/weights.best.RESNET50.hdf5
Epoch 10 took 0.5593855320003058 seconds
6680/6680 [==============================] - 0s - loss: 0.0323 - acc: 0.9985 - val_loss: 0.5509 - val_acc: 0.8383
Epoch 12/20
6400/6680 [===========================>..] - ETA: 0s - loss: 0.0277 - acc: 0.9988Epoch 00011: val_loss did not improve
Epoch 11 took 0.5425587820000146 seconds
6680/6680 [==============================] - 0s - loss: 0.0279 - acc: 0.9987 - val_loss: 0.5512 - val_acc: 0.8383
Epoch 13/20
6336/6680 [===========================>..] - ETA: 0s - loss: 0.0236 - acc: 0.9989Epoch 00012: val_loss did not improve
Epoch 12 took 0.5441269780003495 seconds
6680/6680 [==============================] - 0s - loss: 0.0239 - acc: 0.9988 - val_loss: 0.5554 - val_acc: 0.8407
Epoch 14/20
6400/6680 [===========================>..] - ETA: 0s - loss: 0.0215 - acc: 0.9988Epoch 00013: val_loss did not improve
Epoch 13 took 0.5468552490001457 seconds
6680/6680 [==============================] - 0s - loss: 0.0217 - acc: 0.9987 - val_loss: 0.5568 - val_acc: 0.8347
Epoch 15/20
6400/6680 [===========================>..] - ETA: 0s - loss: 0.0198 - acc: 0.9984Epoch 00014: val_loss did not improve
Epoch 14 took 0.5439025799996671 seconds
6680/6680 [==============================] - 0s - loss: 0.0203 - acc: 0.9984 - val_loss: 0.5592 - val_acc: 0.8287
Epoch 16/20
6400/6680 [===========================>..] - ETA: 0s - loss: 0.0205 - acc: 0.9983Epoch 00015: val_loss did not improve
Epoch 15 took 0.5458991940004125 seconds
6680/6680 [==============================] - 0s - loss: 0.0208 - acc: 0.9981 - val_loss: 0.5609 - val_acc: 0.8419
Epoch 17/20
6400/6680 [===========================>..] - ETA: 0s - loss: 0.0186 - acc: 0.9983Epoch 00016: val_loss did not improve
Epoch 16 took 0.5443005879997145 seconds
6680/6680 [==============================] - 0s - loss: 0.0183 - acc: 0.9984 - val_loss: 0.5557 - val_acc: 0.8371
Epoch 18/20
6400/6680 [===========================>..] - ETA: 0s - loss: 0.0163 - acc: 0.9986Epoch 00017: val_loss did not improve
Epoch 17 took 0.5429084269999294 seconds
6680/6680 [==============================] - 0s - loss: 0.0163 - acc: 0.9985 - val_loss: 0.5526 - val_acc: 0.8419
Epoch 19/20
6400/6680 [===========================>..] - ETA: 0s - loss: 0.0133 - acc: 0.9989Epoch 00018: val_loss did not improve
Epoch 18 took 0.5478009159996873 seconds
6680/6680 [==============================] - 0s - loss: 0.0140 - acc: 0.9988 - val_loss: 0.5734 - val_acc: 0.8395
Epoch 20/20
6336/6680 [===========================>..] - ETA: 0s - loss: 0.0133 - acc: 0.9989Epoch 00019: val_loss did not improve
Epoch 19 took 0.5461943480004265 seconds
6680/6680 [==============================] - 0s - loss: 0.0137 - acc: 0.9987 - val_loss: 0.5728 - val_acc: 0.8479
Training took 11.357930078000209 seconds

(IMPLEMENTATION) Load the Model with the Best Validation Loss

In [81]:
Resnet50_model.load_weights('saved_models/weights.best.RESNET50.hdf5')

(IMPLEMENTATION) Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 60%.

In [82]:
# get index of predicted dog breed for each image in test set
Resnet50_predictions = [np.argmax(Resnet50_model.predict(np.expand_dims(feature, axis=0))) for feature in test_resnet50]

# report test accuracy
test_accuracy = 100*np.sum(np.array(Resnet50_predictions)==np.argmax(test_targets, axis=1))/len(Resnet50_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 82.7751%
In [22]:
# Display some of the result images with correct or incorrect classification
fig = plt.figure(figsize=(20, 12))
for i, idx in enumerate(np.random.choice(test_tensors.shape[0], size=32, replace=False)):
    ax = fig.add_subplot(4, 8, i + 1, xticks=[], yticks=[])
    ax.imshow(np.squeeze(test_tensors[idx]))
    true_idx = np.argmax(test_targets[idx])
    pred_idx = Resnet50_predictions[idx]
    ax.set_title("{}\n({})".format(dog_names[pred_idx], dog_names[true_idx]),
                                  color=("green" if pred_idx == true_idx else "red"))

(IMPLEMENTATION) Predict Dog Breed with the Model

Write a function that takes an image path as input and returns the dog breed (Affenpinscher, Afghan_hound, etc) that is predicted by your model.

Similar to the analogous function in Step 5, your function should have three steps:

  1. Extract the bottleneck features corresponding to the chosen CNN model.
  2. Supply the bottleneck features as input to the model to return the predicted vector. Note that the argmax of this prediction vector gives the index of the predicted dog breed.
  3. Use the dog_names array defined in Step 0 of this notebook to return the corresponding breed.

The functions to extract the bottleneck features can be found in extract_bottleneck_features.py, and they have been imported in an earlier code cell. To obtain the bottleneck features corresponding to your chosen CNN architecture, you need to use the function

extract_{network}

where {network}, in the above filename, should be one of VGG19, Resnet50, InceptionV3, or Xception.

In [83]:
### Function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.
from extract_bottleneck_features import *

def Resnet50_predict_breed(img_path):
    # extract bottleneck features
    bottleneck_feature = extract_Resnet50(path_to_tensor(img_path))
    # obtain predicted vector
    predicted_vector = Resnet50_model.predict(bottleneck_feature)
    # return dog breed that is predicted by the model
    return dog_names[np.argmax(predicted_vector)]

Step 6: Write your Algorithm

Write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,

  • if a dog is detected in the image, return the predicted breed.
  • if a human is detected in the image, return the resembling dog breed.
  • if neither is detected in the image, provide output that indicates an error.

You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the face_detector and dog_detector functions developed above. You are required to use your CNN from Step 5 to predict dog breed.

Some sample output for our algorithm is provided below, but feel free to design your own user experience!

Sample Human Output

(IMPLEMENTATION) Write your Algorithm

In [24]:
import os
import fnmatch

# Helper function to be able to display a matching image for the humans so that we know immediately 
# how the dog breed looks like, we search for the first image in the training data with the correct name.
def find_dog_img(pattern, path):
    for root, dirs, files in os.walk(path):
        for name in files:
            if fnmatch.fnmatch(name, pattern):
                return os.path.join(root, name)
In [26]:
import matplotlib.image as mpimg

def show_image(img_path):
    img = mpimg.imread(img_path)
    fig = plt.figure()
    plt.subplot()
    plt.imshow(img)
    plt.axis('off')
    plt.plot()
In [84]:
def dog_breed_or_similarity(img_path, show_images=False):
    if show_images == True: show_image(img_path)
    if dog_detector(img_path):
        print("Such a nice dog, I would think you are a ...")
        result = Resnet50_predict_breed(img_path)
        print(result)
        sample_dog_img = find_dog_img(result + '*', 'dogImages/train')
        if show_images == True: show_image(sample_dog_img)
        return result
    if face_detector(img_path):
        print("Hello Human, you look like a...")
        result = Resnet50_predict_breed(img_path)
        print(result)
        sample_dog_img = find_dog_img(result + '*', 'dogImages/train')
        if show_images == True: show_image(sample_dog_img)
        return result
    print("Neither dog or human. Make more effort!")
    return "Error"

Step 7: Test Your Algorithm

In this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that you look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?

(IMPLEMENTATION) Test Your Algorithm on Sample Images!

Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.

Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.

Answer: As this week is election in Germany, I took pictures from the major German politicians and ran them through this algorithm. Additionally, I took some human samples from the lfw folder, some private pictures and the pictures of dogs in the images directory and also the remaining images in this folder (network architecture). Overall, this was a really fun experience and the results are quite convincing for such a small project.

The following points of improvement could be done / have been done:

  • Use data augmentation to generate more sample data as the dataset is quite small. Initially, I thought this could be easily done with the method learned in class, however, the bottleneck features are not images and so another architecture has to be used. Will be explored further. Results from other students show that the accuracy gain might not be too big. We need to use a full pre-trained network to feed in the augmented images. This also gives the opportunity for finetuning. See section 9.
  • Use a more complex model at the end of the ResNet: See section 8.
  • Check out another model. Reports on Slack mention that Inception achieves higher performance. As I have just read the ResNet paper, I wanted to use this one for this task. See section 8 for InceptionV3 an Xception results.
  • Additionally, the human detection should be improved. One picture of a human was not classified correctly. (not addressed)
  • It would be nice for the output of the algorithm to show the input image and a sample of the matching dog breed. This is implemented and can be run with the images available, but the images are not checked in due to potential copyright issues.
In [86]:
# Image outputs need to be run online and are not checked in to github
# due to potential copyright 
input_directory = "/home/aind2/AIND-Dog/images"
list_of_files = os.listdir(input_directory)
file1 = 'carsten.png'
img_file = input_directory + '/' + file1
print("Working on file... ", img_file)
dog_breed_or_similarity(img_file, True)
Working on file...  /home/aind2/AIND-Dog/images/carsten.png
Hello Human, you look like a...
Xoloitzcuintli
Out[86]:
'Xoloitzcuintli'
In [ ]:
# Image outputs need to be run online and are not checked in to github
# due to potential copyright 
input_directory = "/home/aind2/AIND-Dog/images"
list_of_files = os.listdir(input_directory)
file1 = 'Angela_Merkel.jpg'
img_file = input_directory + '/' + file1
print("Working on file... ", img_file)
dog_breed_or_similarity(img_file, True)
In [85]:
import os

input_directory = "/home/aind2/AIND-Dog/images"
list_of_files = os.listdir(input_directory)
for file_name in list_of_files:
    img_file = input_directory + '/' + file_name
    print("Working on file... ", img_file)
    # Somehow it looks like the plotting doesn't work easily in the loop
    # So I would need to generate a nice table in the future...
    # But it would be more reasonable to put this into an app anyway.
    dog_breed_or_similarity(img_file)
    print("-------------------------")
Working on file...  /home/aind2/AIND-Dog/images/Ursula_von_der_Leyen.jpg
Hello Human, you look like a...
Nova_scotia_duck_tolling_retriever
-------------------------
Working on file...  /home/aind2/AIND-Dog/images/Andrea_Bocelli.jpg
Hello Human, you look like a...
American_water_spaniel
-------------------------
Working on file...  /home/aind2/AIND-Dog/images/Angela_Merkel.jpg
Hello Human, you look like a...
Dachshund
-------------------------
Working on file...  /home/aind2/AIND-Dog/images/Sigmar_Gabriel.jpg
Hello Human, you look like a...
American_foxhound
-------------------------
Working on file...  /home/aind2/AIND-Dog/images/Charlie_Sheen.jpg
Hello Human, you look like a...
Chesapeake_bay_retriever
-------------------------
Working on file...  /home/aind2/AIND-Dog/images/girl2.png
Hello Human, you look like a...
Chihuahua
-------------------------
Working on file...  /home/aind2/AIND-Dog/images/Curly-coated_retriever_03896.jpg
Such a nice dog, I would think you are a ...
Curly-coated_retriever
-------------------------
Working on file...  /home/aind2/AIND-Dog/images/carsten.png
Hello Human, you look like a...
Xoloitzcuintli
-------------------------
Working on file...  /home/aind2/AIND-Dog/images/Anna_Kournikova.jpg
Hello Human, you look like a...
Nova_scotia_duck_tolling_retriever
-------------------------
Working on file...  /home/aind2/AIND-Dog/images/Anna_Nicole_Smith.jpg
Hello Human, you look like a...
Cavalier_king_charles_spaniel
-------------------------
Working on file...  /home/aind2/AIND-Dog/images/Labrador_retriever_06455.jpg
Such a nice dog, I would think you are a ...
Labrador_retriever
-------------------------
Working on file...  /home/aind2/AIND-Dog/images/Labrador_retriever_06449.jpg
Such a nice dog, I would think you are a ...
Labrador_retriever
-------------------------
Working on file...  /home/aind2/AIND-Dog/images/sample_cnn.png
Neither dog or human. Make more effort!
-------------------------
Working on file...  /home/aind2/AIND-Dog/images/sample_human_output.png
Hello Human, you look like a...
Norwegian_lundehund
-------------------------
Working on file...  /home/aind2/AIND-Dog/images/sample_dog_output.png
Neither dog or human. Make more effort!
-------------------------
Working on file...  /home/aind2/AIND-Dog/images/Welsh_springer_spaniel_08203.jpg
Such a nice dog, I would think you are a ...
Welsh_springer_spaniel
-------------------------
Working on file...  /home/aind2/AIND-Dog/images/Cem_Oezdemir.jpg
Hello Human, you look like a...
Silky_terrier
-------------------------
Working on file...  /home/aind2/AIND-Dog/images/girl3.png
Hello Human, you look like a...
Chihuahua
-------------------------
Working on file...  /home/aind2/AIND-Dog/images/girl1.png
Neither dog or human. Make more effort!
-------------------------
Working on file...  /home/aind2/AIND-Dog/images/Labrador_retriever_06457.jpg
Such a nice dog, I would think you are a ...
Labrador_retriever
-------------------------
Working on file...  /home/aind2/AIND-Dog/images/woman.png
Hello Human, you look like a...
Chihuahua
-------------------------
Working on file...  /home/aind2/AIND-Dog/images/American_water_spaniel_00648.jpg
Such a nice dog, I would think you are a ...
American_water_spaniel
-------------------------
Working on file...  /home/aind2/AIND-Dog/images/golden-retriever.jpg
Such a nice dog, I would think you are a ...
Golden_retriever
-------------------------
Working on file...  /home/aind2/AIND-Dog/images/Brittany_02625.jpg
Such a nice dog, I would think you are a ...
Brittany
-------------------------
Working on file...  /home/aind2/AIND-Dog/images/Martin-Schulz.jpg
Hello Human, you look like a...
French_bulldog
-------------------------
Working on file...  /home/aind2/AIND-Dog/images/cat.jpg
Neither dog or human. Make more effort!
-------------------------

Step 8: Extensions

Evaluate two other models: Inception and Xception and play around with the top layers.

In [32]:
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential

# Build Inception model
inception_bottleneck_features = np.load('bottleneck_features/DogInceptionV3Data.npz')
train_inception = inception_bottleneck_features['train']
valid_inception = inception_bottleneck_features['valid']
test_inception = inception_bottleneck_features['test']

Inception_model = Sequential()
Inception_model.add(GlobalAveragePooling2D(input_shape=train_inception.shape[1:]))
#Inception_model.add(Dense(64, activation='relu'))
#Inception_model.add(Dropout(0.3))

# Check out again...
#Inception_model.add(Flatten(input_shape=train_data.shape[1:]))
#Inception_model.add(Dense(256, activation='relu'))
#Inception_model.add(Dropout(0.5))

Inception_model.add(Dense(133, activation='softmax'))

Inception_model.summary()

Inception_model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_2 ( (None, 2048)              0         
_________________________________________________________________
dense_4 (Dense)              (None, 133)               272517    
=================================================================
Total params: 272,517
Trainable params: 272,517
Non-trainable params: 0
_________________________________________________________________
In [33]:
from keras.callbacks import ModelCheckpoint  

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.INCEPTION.hdf5', 
                               verbose=1, save_best_only=True)
epochtimer = EpochTimer()

hist = Inception_model.fit(train_inception, train_targets, 
              validation_data=(valid_inception, valid_targets),
              epochs=25, batch_size=32, callbacks=[checkpointer, epochtimer], verbose=1)

show_history_graph(hist)
Train on 6680 samples, validate on 835 samples
Epoch 1/25
6624/6680 [============================>.] - ETA: 0s - loss: 1.2945 - acc: 0.6840Epoch 00000: val_loss improved from inf to 0.59541, saving model to saved_models/weights.best.INCEPTION.hdf5
Epoch 0 took 3.942861465999158 seconds
6680/6680 [==============================] - 3s - loss: 1.2872 - acc: 0.6858 - val_loss: 0.5954 - val_acc: 0.8132
Epoch 2/25
6592/6680 [============================>.] - ETA: 0s - loss: 0.3914 - acc: 0.8765Epoch 00001: val_loss improved from 0.59541 to 0.57415, saving model to saved_models/weights.best.INCEPTION.hdf5
Epoch 1 took 2.2142944610004633 seconds
6680/6680 [==============================] - 2s - loss: 0.3919 - acc: 0.8765 - val_loss: 0.5741 - val_acc: 0.8287
Epoch 3/25
6496/6680 [============================>.] - ETA: 0s - loss: 0.2419 - acc: 0.9216Epoch 00002: val_loss improved from 0.57415 to 0.54491, saving model to saved_models/weights.best.INCEPTION.hdf5
Epoch 2 took 2.213953369000592 seconds
6680/6680 [==============================] - 2s - loss: 0.2423 - acc: 0.9219 - val_loss: 0.5449 - val_acc: 0.8335
Epoch 4/25
6656/6680 [============================>.] - ETA: 0s - loss: 0.1570 - acc: 0.9533Epoch 00003: val_loss did not improve
Epoch 3 took 2.2115754810001818 seconds
6680/6680 [==============================] - 2s - loss: 0.1572 - acc: 0.9530 - val_loss: 0.5819 - val_acc: 0.8395
Epoch 5/25
6560/6680 [============================>.] - ETA: 0s - loss: 0.1105 - acc: 0.9700Epoch 00004: val_loss did not improve
Epoch 4 took 2.113845156000025 seconds
6680/6680 [==============================] - 2s - loss: 0.1116 - acc: 0.9695 - val_loss: 0.5580 - val_acc: 0.8323
Epoch 6/25
6528/6680 [============================>.] - ETA: 0s - loss: 0.0759 - acc: 0.9830Epoch 00005: val_loss did not improve
Epoch 5 took 2.1403316340001766 seconds
6680/6680 [==============================] - 2s - loss: 0.0761 - acc: 0.9826 - val_loss: 0.5451 - val_acc: 0.8419
Epoch 7/25
6656/6680 [============================>.] - ETA: 0s - loss: 0.0562 - acc: 0.9899Epoch 00006: val_loss did not improve
Epoch 6 took 2.1431490129998565 seconds
6680/6680 [==============================] - 2s - loss: 0.0561 - acc: 0.9900 - val_loss: 0.5463 - val_acc: 0.8551
Epoch 8/25
6560/6680 [============================>.] - ETA: 0s - loss: 0.0447 - acc: 0.9913Epoch 00007: val_loss did not improve
Epoch 7 took 2.061810305000108 seconds
6680/6680 [==============================] - 2s - loss: 0.0448 - acc: 0.9913 - val_loss: 0.5517 - val_acc: 0.8575
Epoch 9/25
6560/6680 [============================>.] - ETA: 0s - loss: 0.0398 - acc: 0.9919Epoch 00008: val_loss did not improve
Epoch 8 took 2.099276237000595 seconds
6680/6680 [==============================] - 2s - loss: 0.0404 - acc: 0.9915 - val_loss: 0.5610 - val_acc: 0.8491
Epoch 10/25
6624/6680 [============================>.] - ETA: 0s - loss: 0.0423 - acc: 0.9920Epoch 00009: val_loss did not improve
Epoch 9 took 2.159993620000023 seconds
6680/6680 [==============================] - 2s - loss: 0.0421 - acc: 0.9921 - val_loss: 0.5473 - val_acc: 0.8611
Epoch 11/25
6560/6680 [============================>.] - ETA: 0s - loss: 0.0274 - acc: 0.9956Epoch 00010: val_loss did not improve
Epoch 10 took 2.053733941000246 seconds
6680/6680 [==============================] - 2s - loss: 0.0273 - acc: 0.9957 - val_loss: 0.5794 - val_acc: 0.8551
Epoch 12/25
6560/6680 [============================>.] - ETA: 0s - loss: 0.0251 - acc: 0.9956Epoch 00011: val_loss did not improve
Epoch 11 took 2.0476838590002444 seconds
6680/6680 [==============================] - 2s - loss: 0.0252 - acc: 0.9957 - val_loss: 0.5844 - val_acc: 0.8587
Epoch 13/25
6624/6680 [============================>.] - ETA: 0s - loss: 0.0216 - acc: 0.9956Epoch 00012: val_loss did not improve
Epoch 12 took 2.1659428809998644 seconds
6680/6680 [==============================] - 2s - loss: 0.0216 - acc: 0.9957 - val_loss: 0.5947 - val_acc: 0.8647
Epoch 14/25
6592/6680 [============================>.] - ETA: 0s - loss: 0.0214 - acc: 0.9961Epoch 00013: val_loss did not improve
Epoch 13 took 2.273303461000978 seconds
6680/6680 [==============================] - 2s - loss: 0.0215 - acc: 0.9961 - val_loss: 0.6010 - val_acc: 0.8563
Epoch 15/25
6656/6680 [============================>.] - ETA: 0s - loss: 0.0150 - acc: 0.9979Epoch 00014: val_loss did not improve
Epoch 14 took 2.3107379140001285 seconds
6680/6680 [==============================] - 2s - loss: 0.0150 - acc: 0.9979 - val_loss: 0.6233 - val_acc: 0.8671
Epoch 16/25
6624/6680 [============================>.] - ETA: 0s - loss: 0.0154 - acc: 0.9970Epoch 00015: val_loss did not improve
Epoch 15 took 2.3202547849996336 seconds
6680/6680 [==============================] - 2s - loss: 0.0159 - acc: 0.9969 - val_loss: 0.6446 - val_acc: 0.8635
Epoch 17/25
6624/6680 [============================>.] - ETA: 0s - loss: 0.0168 - acc: 0.9961Epoch 00016: val_loss did not improve
Epoch 16 took 2.225089449000734 seconds
6680/6680 [==============================] - 2s - loss: 0.0167 - acc: 0.9961 - val_loss: 0.6139 - val_acc: 0.8623
Epoch 18/25
6496/6680 [============================>.] - ETA: 0s - loss: 0.0127 - acc: 0.9983Epoch 00017: val_loss did not improve
Epoch 17 took 2.1878028379996977 seconds
6680/6680 [==============================] - 2s - loss: 0.0126 - acc: 0.9984 - val_loss: 0.6152 - val_acc: 0.8635
Epoch 19/25
6496/6680 [============================>.] - ETA: 0s - loss: 0.0142 - acc: 0.9968Epoch 00018: val_loss did not improve
Epoch 18 took 2.228407591001087 seconds
6680/6680 [==============================] - 2s - loss: 0.0141 - acc: 0.9967 - val_loss: 0.6423 - val_acc: 0.8539
Epoch 20/25
6592/6680 [============================>.] - ETA: 0s - loss: 0.0140 - acc: 0.9967Epoch 00019: val_loss did not improve
Epoch 19 took 2.1718268290005653 seconds
6680/6680 [==============================] - 2s - loss: 0.0140 - acc: 0.9967 - val_loss: 0.6390 - val_acc: 0.8623
Epoch 21/25
6656/6680 [============================>.] - ETA: 0s - loss: 0.0106 - acc: 0.9974Epoch 00020: val_loss did not improve
Epoch 20 took 2.2135516990001634 seconds
6680/6680 [==============================] - 2s - loss: 0.0105 - acc: 0.9975 - val_loss: 0.6322 - val_acc: 0.8635
Epoch 22/25
6560/6680 [============================>.] - ETA: 0s - loss: 0.0206 - acc: 0.9953Epoch 00021: val_loss did not improve
Epoch 21 took 2.2642928900004335 seconds
6680/6680 [==============================] - 2s - loss: 0.0213 - acc: 0.9951 - val_loss: 0.6659 - val_acc: 0.8635
Epoch 23/25
6592/6680 [============================>.] - ETA: 0s - loss: 0.1265 - acc: 0.9642Epoch 00022: val_loss did not improve
Epoch 22 took 2.2040127140007826 seconds
6680/6680 [==============================] - 2s - loss: 0.1288 - acc: 0.9638 - val_loss: 1.0895 - val_acc: 0.7952
Epoch 24/25
6528/6680 [============================>.] - ETA: 0s - loss: 0.1691 - acc: 0.9521Epoch 00023: val_loss did not improve
Epoch 23 took 2.2483151279993763 seconds
6680/6680 [==============================] - 2s - loss: 0.1669 - acc: 0.9522 - val_loss: 0.9598 - val_acc: 0.8287
Epoch 25/25
6592/6680 [============================>.] - ETA: 0s - loss: 0.0501 - acc: 0.9836Epoch 00024: val_loss did not improve
Epoch 24 took 2.1148111399998015 seconds
6680/6680 [==============================] - 2s - loss: 0.0495 - acc: 0.9838 - val_loss: 0.8529 - val_acc: 0.8443
Training took 56.360994185999516 seconds

Testing

In [34]:
Inception_model.load_weights('saved_models/weights.best.INCEPTION.hdf5')

# get index of predicted dog breed for each image in test set
Inception_predictions = [np.argmax(Inception_model.predict(np.expand_dims(feature, axis=0))) for feature in test_inception]

# report test accuracy
test_accuracy = 100*np.sum(np.array(Inception_predictions)==np.argmax(test_targets, axis=1))/len(Inception_predictions)
print('Test accuracy Inception: %.4f%%' % test_accuracy)
Test accuracy Inception: 80.3828%

XCeption

In [38]:
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense, LeakyReLU
from keras.models import Sequential

# Build Xception model
xception_bottleneck_features = np.load('bottleneck_features/DogXceptionData.npz')
train_xception = xception_bottleneck_features['train']
valid_xception = xception_bottleneck_features['valid']
test_xception = xception_bottleneck_features['test']

Xception_model = Sequential()
Xception_model.add(GlobalAveragePooling2D(input_shape=train_inception.shape[1:]))
#Xception_model.add(Dense(64, activation='relu'))
#Xception_model.add(Dropout(0.3))
Xception_model.add(LeakyReLU(alpha=0.3))
Xception_model.add(Dense(512, activation='relu'))
Xception_model.add(LeakyReLU(alpha=0.3))

Xception_model.add(Dense(133, activation='softmax'))

Xception_model.summary()

Xception_model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_5 ( (None, 2048)              0         
_________________________________________________________________
leaky_re_lu_3 (LeakyReLU)    (None, 2048)              0         
_________________________________________________________________
dense_7 (Dense)              (None, 512)               1049088   
_________________________________________________________________
leaky_re_lu_4 (LeakyReLU)    (None, 512)               0         
_________________________________________________________________
dense_8 (Dense)              (None, 133)               68229     
=================================================================
Total params: 1,117,317
Trainable params: 1,117,317
Non-trainable params: 0
_________________________________________________________________
In [39]:
from keras.callbacks import ModelCheckpoint  

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.XCEPTION.hdf5', 
                               verbose=1, save_best_only=True)
epochtimer = EpochTimer()

hist = Xception_model.fit(train_xception, train_targets, 
              validation_data=(valid_xception, valid_targets),
              epochs=25, batch_size=32, callbacks=[checkpointer, epochtimer], verbose=1)

show_history_graph(hist)
Train on 6680 samples, validate on 835 samples
Epoch 1/25
6656/6680 [============================>.] - ETA: 0s - loss: 1.2026 - acc: 0.7012Epoch 00000: val_loss improved from inf to 0.67853, saving model to saved_models/weights.best.XCEPTION.hdf5
Epoch 0 took 5.58935638299954 seconds
6680/6680 [==============================] - 5s - loss: 1.1997 - acc: 0.7018 - val_loss: 0.6785 - val_acc: 0.7892
Epoch 2/25
6656/6680 [============================>.] - ETA: 0s - loss: 0.4407 - acc: 0.8619Epoch 00001: val_loss improved from 0.67853 to 0.61167, saving model to saved_models/weights.best.XCEPTION.hdf5
Epoch 1 took 4.028750924000633 seconds
6680/6680 [==============================] - 4s - loss: 0.4400 - acc: 0.8620 - val_loss: 0.6117 - val_acc: 0.8240
Epoch 3/25
6656/6680 [============================>.] - ETA: 0s - loss: 0.2816 - acc: 0.9073Epoch 00002: val_loss improved from 0.61167 to 0.58780, saving model to saved_models/weights.best.XCEPTION.hdf5
Epoch 2 took 4.160214785999415 seconds
6680/6680 [==============================] - 4s - loss: 0.2813 - acc: 0.9073 - val_loss: 0.5878 - val_acc: 0.8204
Epoch 4/25
6656/6680 [============================>.] - ETA: 0s - loss: 0.1990 - acc: 0.9345Epoch 00003: val_loss improved from 0.58780 to 0.56179, saving model to saved_models/weights.best.XCEPTION.hdf5
Epoch 3 took 4.172967988999517 seconds
6680/6680 [==============================] - 4s - loss: 0.1992 - acc: 0.9344 - val_loss: 0.5618 - val_acc: 0.8204
Epoch 5/25
6592/6680 [============================>.] - ETA: 0s - loss: 0.1398 - acc: 0.9546Epoch 00004: val_loss improved from 0.56179 to 0.55424, saving model to saved_models/weights.best.XCEPTION.hdf5
Epoch 4 took 4.099528204000308 seconds
6680/6680 [==============================] - 4s - loss: 0.1400 - acc: 0.9546 - val_loss: 0.5542 - val_acc: 0.8419
Epoch 6/25
6656/6680 [============================>.] - ETA: 0s - loss: 0.1055 - acc: 0.9650Epoch 00005: val_loss did not improve
Epoch 5 took 4.0995213969999895 seconds
6680/6680 [==============================] - 4s - loss: 0.1069 - acc: 0.9645 - val_loss: 0.6176 - val_acc: 0.8299
Epoch 7/25
6656/6680 [============================>.] - ETA: 0s - loss: 0.0824 - acc: 0.9754Epoch 00006: val_loss did not improve
Epoch 6 took 4.158576555999389 seconds
6680/6680 [==============================] - 4s - loss: 0.0828 - acc: 0.9751 - val_loss: 0.6252 - val_acc: 0.8275
Epoch 8/25
6656/6680 [============================>.] - ETA: 0s - loss: 0.0612 - acc: 0.9812Epoch 00007: val_loss did not improve
Epoch 7 took 4.155512138999256 seconds
6680/6680 [==============================] - 4s - loss: 0.0613 - acc: 0.9811 - val_loss: 0.5920 - val_acc: 0.8551
Epoch 9/25
6656/6680 [============================>.] - ETA: 0s - loss: 0.0645 - acc: 0.9805Epoch 00008: val_loss did not improve
Epoch 8 took 4.152746734000175 seconds
6680/6680 [==============================] - 4s - loss: 0.0643 - acc: 0.9805 - val_loss: 0.7000 - val_acc: 0.8371
Epoch 10/25
6656/6680 [============================>.] - ETA: 0s - loss: 0.0677 - acc: 0.9808Epoch 00009: val_loss did not improve
Epoch 9 took 4.108746455000073 seconds
6680/6680 [==============================] - 4s - loss: 0.0678 - acc: 0.9807 - val_loss: 0.6686 - val_acc: 0.8431
Epoch 11/25
6656/6680 [============================>.] - ETA: 0s - loss: 0.0664 - acc: 0.9802Epoch 00010: val_loss did not improve
Epoch 10 took 4.045012177000899 seconds
6680/6680 [==============================] - 4s - loss: 0.0662 - acc: 0.9802 - val_loss: 0.6852 - val_acc: 0.8311
Epoch 12/25
6656/6680 [============================>.] - ETA: 0s - loss: 0.0593 - acc: 0.9817Epoch 00011: val_loss did not improve
Epoch 11 took 4.023451143000784 seconds
6680/6680 [==============================] - 4s - loss: 0.0592 - acc: 0.9817 - val_loss: 0.6932 - val_acc: 0.8407
Epoch 13/25
6656/6680 [============================>.] - ETA: 0s - loss: 0.0417 - acc: 0.9890Epoch 00012: val_loss did not improve
Epoch 12 took 4.0056529700013925 seconds
6680/6680 [==============================] - 4s - loss: 0.0417 - acc: 0.9891 - val_loss: 0.7407 - val_acc: 0.8419
Epoch 14/25
6656/6680 [============================>.] - ETA: 0s - loss: 0.0469 - acc: 0.9869Epoch 00013: val_loss did not improve
Epoch 13 took 4.097945048999463 seconds
6680/6680 [==============================] - 4s - loss: 0.0469 - acc: 0.9868 - val_loss: 0.6608 - val_acc: 0.8443
Epoch 15/25
6656/6680 [============================>.] - ETA: 0s - loss: 0.0445 - acc: 0.9875Epoch 00014: val_loss did not improve
Epoch 14 took 4.14142877499944 seconds
6680/6680 [==============================] - 4s - loss: 0.0443 - acc: 0.9876 - val_loss: 0.6776 - val_acc: 0.8467
Epoch 16/25
6656/6680 [============================>.] - ETA: 0s - loss: 0.0393 - acc: 0.9877Epoch 00015: val_loss did not improve
Epoch 15 took 4.198758106000241 seconds
6680/6680 [==============================] - 4s - loss: 0.0391 - acc: 0.9877 - val_loss: 0.7548 - val_acc: 0.8335
Epoch 17/25
6656/6680 [============================>.] - ETA: 0s - loss: 0.0892 - acc: 0.9755Epoch 00016: val_loss did not improve
Epoch 16 took 4.1869977559999825 seconds
6680/6680 [==============================] - 4s - loss: 0.0891 - acc: 0.9754 - val_loss: 0.7896 - val_acc: 0.8275
Epoch 18/25
6656/6680 [============================>.] - ETA: 0s - loss: 0.0939 - acc: 0.9736Epoch 00017: val_loss did not improve
Epoch 17 took 4.1372682300007 seconds
6680/6680 [==============================] - 4s - loss: 0.0936 - acc: 0.9737 - val_loss: 0.7007 - val_acc: 0.8299
Epoch 19/25
6656/6680 [============================>.] - ETA: 0s - loss: 0.0841 - acc: 0.9757Epoch 00018: val_loss did not improve
Epoch 18 took 4.179409575001046 seconds
6680/6680 [==============================] - 4s - loss: 0.0839 - acc: 0.9757 - val_loss: 0.7940 - val_acc: 0.8311
Epoch 20/25
6656/6680 [============================>.] - ETA: 0s - loss: 0.0442 - acc: 0.9874Epoch 00019: val_loss did not improve
Epoch 19 took 4.130311273998814 seconds
6680/6680 [==============================] - 4s - loss: 0.0441 - acc: 0.9874 - val_loss: 0.8007 - val_acc: 0.8383
Epoch 21/25
6656/6680 [============================>.] - ETA: 0s - loss: 0.0325 - acc: 0.9911Epoch 00020: val_loss did not improve
Epoch 20 took 4.1006561029989825 seconds
6680/6680 [==============================] - 4s - loss: 0.0325 - acc: 0.9912 - val_loss: 0.7948 - val_acc: 0.8347
Epoch 22/25
6656/6680 [============================>.] - ETA: 0s - loss: 0.0477 - acc: 0.9880Epoch 00021: val_loss did not improve
Epoch 21 took 4.120546510999702 seconds
6680/6680 [==============================] - 4s - loss: 0.0475 - acc: 0.9880 - val_loss: 0.8234 - val_acc: 0.8371
Epoch 23/25
6656/6680 [============================>.] - ETA: 0s - loss: 0.0376 - acc: 0.9896Epoch 00022: val_loss did not improve
Epoch 22 took 4.029697253999984 seconds
6680/6680 [==============================] - 4s - loss: 0.0374 - acc: 0.9897 - val_loss: 0.8064 - val_acc: 0.8371
Epoch 24/25
6656/6680 [============================>.] - ETA: 0s - loss: 0.0452 - acc: 0.9871Epoch 00023: val_loss did not improve
Epoch 23 took 4.040230100001281 seconds
6680/6680 [==============================] - 4s - loss: 0.0451 - acc: 0.9870 - val_loss: 0.8370 - val_acc: 0.8467
Epoch 25/25
6656/6680 [============================>.] - ETA: 0s - loss: 0.0340 - acc: 0.9904Epoch 00024: val_loss did not improve
Epoch 24 took 4.031899678000627 seconds
6680/6680 [==============================] - 4s - loss: 0.0339 - acc: 0.9904 - val_loss: 0.7892 - val_acc: 0.8407
Training took 104.2245341279995 seconds
In [40]:
Xception_model.load_weights('saved_models/weights.best.XCEPTION.hdf5')

# get index of predicted dog breed for each image in test set
Xception_predictions = [np.argmax(Xception_model.predict(np.expand_dims(feature, axis=0))) for feature in test_xception]

# report test accuracy
test_accuracy = 100*np.sum(np.array(Xception_predictions)==np.argmax(test_targets, axis=1))/len(Xception_predictions)
print('Test accuracy xception: %.4f%%' % test_accuracy)
Test accuracy xception: 84.0909%
In [41]:
fig = plt.figure(figsize=(20, 12))
for i, idx in enumerate(np.random.choice(test_tensors.shape[0], size=32, replace=False)):
    ax = fig.add_subplot(4, 8, i + 1, xticks=[], yticks=[])
    ax.imshow(np.squeeze(test_tensors[idx]))
    true_idx = np.argmax(test_targets[idx])
    pred_idx = Xception_predictions[idx]
    ax.set_title("{}\n({})".format(dog_names[pred_idx], dog_names[true_idx]),
                                  color=("green" if pred_idx == true_idx else "red"))

Results

  1. The first extension experiment was with an exact copy of the previous ResNet architecture, just using the InceptionV3 bottleneck network upfront. This resulted in a test accuracy of: 82.7751%, i.e. worse than the Resnet50. The optimum result was already reached after 8 epochs, meaning that the architecture again did serious overfitting. In follow up experiments, this accuracy changed sometimes. One result was 80.3828%.

  2. The second extension experiment was changing the network architecture. I tried, not to use the GlobalAveragePooling layer, but instead flatten the data and then connect another dense layer. Although the number of parameters were not so high (around 500,000), this model ran into the problem of resource allocation and could not be solved.

  3. The third experiment was keeping the GlobalAveragePooling, but add another dense layer with dropouts. This resulted in an accuracy of 80.8612%. Again worse than before.

  4. I tested the XCeption network with a top network using two LeakyReLus and a fully connected layer with 512 nodes. This resulted in an accuracy of 84.0909%, which is comparable to the ResNet50 performance, but involves a much more complicated network and longer training times. As can be seen in the figures, this network reached its accurcy peak for validation quite early and overfitted afterwards.

TODO: Playing around with batch size and optimizer.

9. Step Data Augmentation with Finetuning

As it is not possible to use data augmentation with the bottleneck models, the whole network has to be used.

As mentioned above I had a look at this tutorial Keras. However, it was not possible for me to build the network based on this information. So, I did a research on the Slack channels and found the excellent notebook and app of Jay Madhava. Most parts of the following code are taken from there, but with my own modifications and experiments to learn the transfer and fine tuning.

In [42]:
# InceptionV3 uses 299 x 299 images instead of the 224 x 224 above
# So we need to generate another set of input tensors.
from keras.applications.inception_v3 import preprocess_input
from tqdm import tqdm

def paths_to_inception_tensor(img_paths, width=299, height=299):
    list_of_tensors = [preprocess_input(path_to_tensor(img_path, width, height)) for img_path in tqdm(img_paths)]
    return np.vstack(list_of_tensors)

inception_test_tensors = paths_to_inception_tensor(test_files)
100%|██████████| 836/836 [00:06<00:00, 127.99it/s]
In [43]:
from keras.applications.inception_v3 import InceptionV3, preprocess_input
from keras.preprocessing.image import ImageDataGenerator

img_width, img_height = 299, 299
batch_size = 100
num_classes = 133
train_dir = 'dogImages/train'
valid_dir = 'dogImages/valid'

# Data augmentation basically in the same way it was introduced with the cifar-10 dataset
# Here we also use shear and zoom as the images are larger.
train_datagen = ImageDataGenerator(
    preprocessing_function=preprocess_input,
    rotation_range=20,
    width_shift_range=0.2,
    height_shift_range=0.2,
    shear_range=0.2,
    zoom_range=0.2,
    horizontal_flip=True
)

# Same operation on the validation set
validation_datagen = ImageDataGenerator(
    preprocessing_function=preprocess_input,
    rotation_range=20,
    width_shift_range=0.2,
    height_shift_range=0.2,
    shear_range=0.2,
    zoom_range=0.2,
    horizontal_flip=True
)

train_generator = train_datagen.flow_from_directory(
    train_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
)

validation_generator = validation_datagen.flow_from_directory(
    valid_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
)
Found 6680 images belonging to 133 classes.
Found 835 images belonging to 133 classes.
In [46]:
from keras.models import Model
import math

# Load Inception model without the top layers
base_model = InceptionV3(weights='imagenet', include_top=False)

# Freeze all layers so that the weights cannot be updated
for layer in base_model.layers:
    layer.trainable = False

# Construct our own model on top of Inception network
# First use same architecture as above with just GlobalAveragePooling and a dense layer
output = base_model.output
output = GlobalAveragePooling2D()(output)
#output = Dense(512, activation='relu')(output)
top_layers = Dense(133, activation='softmax')(output)

finetune_model = Model(inputs=base_model.input, outputs=top_layers)

finetune_model.summary()

finetune_model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
____________________________________________________________________________________________________
Layer (type)                     Output Shape          Param #     Connected to                     
====================================================================================================
input_7 (InputLayer)             (None, None, None, 3) 0                                            
____________________________________________________________________________________________________
conv2d_99 (Conv2D)               (None, None, None, 32 864         input_7[0][0]                    
____________________________________________________________________________________________________
batch_normalization_95 (BatchNor (None, None, None, 32 96          conv2d_99[0][0]                  
____________________________________________________________________________________________________
activation_340 (Activation)      (None, None, None, 32 0           batch_normalization_95[0][0]     
____________________________________________________________________________________________________
conv2d_100 (Conv2D)              (None, None, None, 32 9216        activation_340[0][0]             
____________________________________________________________________________________________________
batch_normalization_96 (BatchNor (None, None, None, 32 96          conv2d_100[0][0]                 
____________________________________________________________________________________________________
activation_341 (Activation)      (None, None, None, 32 0           batch_normalization_96[0][0]     
____________________________________________________________________________________________________
conv2d_101 (Conv2D)              (None, None, None, 64 18432       activation_341[0][0]             
____________________________________________________________________________________________________
batch_normalization_97 (BatchNor (None, None, None, 64 192         conv2d_101[0][0]                 
____________________________________________________________________________________________________
activation_342 (Activation)      (None, None, None, 64 0           batch_normalization_97[0][0]     
____________________________________________________________________________________________________
max_pooling2d_12 (MaxPooling2D)  (None, None, None, 64 0           activation_342[0][0]             
____________________________________________________________________________________________________
conv2d_102 (Conv2D)              (None, None, None, 80 5120        max_pooling2d_12[0][0]           
____________________________________________________________________________________________________
batch_normalization_98 (BatchNor (None, None, None, 80 240         conv2d_102[0][0]                 
____________________________________________________________________________________________________
activation_343 (Activation)      (None, None, None, 80 0           batch_normalization_98[0][0]     
____________________________________________________________________________________________________
conv2d_103 (Conv2D)              (None, None, None, 19 138240      activation_343[0][0]             
____________________________________________________________________________________________________
batch_normalization_99 (BatchNor (None, None, None, 19 576         conv2d_103[0][0]                 
____________________________________________________________________________________________________
activation_344 (Activation)      (None, None, None, 19 0           batch_normalization_99[0][0]     
____________________________________________________________________________________________________
max_pooling2d_13 (MaxPooling2D)  (None, None, None, 19 0           activation_344[0][0]             
____________________________________________________________________________________________________
conv2d_107 (Conv2D)              (None, None, None, 64 12288       max_pooling2d_13[0][0]           
____________________________________________________________________________________________________
batch_normalization_103 (BatchNo (None, None, None, 64 192         conv2d_107[0][0]                 
____________________________________________________________________________________________________
activation_348 (Activation)      (None, None, None, 64 0           batch_normalization_103[0][0]    
____________________________________________________________________________________________________
conv2d_105 (Conv2D)              (None, None, None, 48 9216        max_pooling2d_13[0][0]           
____________________________________________________________________________________________________
conv2d_108 (Conv2D)              (None, None, None, 96 55296       activation_348[0][0]             
____________________________________________________________________________________________________
batch_normalization_101 (BatchNo (None, None, None, 48 144         conv2d_105[0][0]                 
____________________________________________________________________________________________________
batch_normalization_104 (BatchNo (None, None, None, 96 288         conv2d_108[0][0]                 
____________________________________________________________________________________________________
activation_346 (Activation)      (None, None, None, 48 0           batch_normalization_101[0][0]    
____________________________________________________________________________________________________
activation_349 (Activation)      (None, None, None, 96 0           batch_normalization_104[0][0]    
____________________________________________________________________________________________________
average_pooling2d_10 (AveragePoo (None, None, None, 19 0           max_pooling2d_13[0][0]           
____________________________________________________________________________________________________
conv2d_104 (Conv2D)              (None, None, None, 64 12288       max_pooling2d_13[0][0]           
____________________________________________________________________________________________________
conv2d_106 (Conv2D)              (None, None, None, 64 76800       activation_346[0][0]             
____________________________________________________________________________________________________
conv2d_109 (Conv2D)              (None, None, None, 96 82944       activation_349[0][0]             
____________________________________________________________________________________________________
conv2d_110 (Conv2D)              (None, None, None, 32 6144        average_pooling2d_10[0][0]       
____________________________________________________________________________________________________
batch_normalization_100 (BatchNo (None, None, None, 64 192         conv2d_104[0][0]                 
____________________________________________________________________________________________________
batch_normalization_102 (BatchNo (None, None, None, 64 192         conv2d_106[0][0]                 
____________________________________________________________________________________________________
batch_normalization_105 (BatchNo (None, None, None, 96 288         conv2d_109[0][0]                 
____________________________________________________________________________________________________
batch_normalization_106 (BatchNo (None, None, None, 32 96          conv2d_110[0][0]                 
____________________________________________________________________________________________________
activation_345 (Activation)      (None, None, None, 64 0           batch_normalization_100[0][0]    
____________________________________________________________________________________________________
activation_347 (Activation)      (None, None, None, 64 0           batch_normalization_102[0][0]    
____________________________________________________________________________________________________
activation_350 (Activation)      (None, None, None, 96 0           batch_normalization_105[0][0]    
____________________________________________________________________________________________________
activation_351 (Activation)      (None, None, None, 32 0           batch_normalization_106[0][0]    
____________________________________________________________________________________________________
mixed0 (Concatenate)             (None, None, None, 25 0           activation_345[0][0]             
                                                                   activation_347[0][0]             
                                                                   activation_350[0][0]             
                                                                   activation_351[0][0]             
____________________________________________________________________________________________________
conv2d_114 (Conv2D)              (None, None, None, 64 16384       mixed0[0][0]                     
____________________________________________________________________________________________________
batch_normalization_110 (BatchNo (None, None, None, 64 192         conv2d_114[0][0]                 
____________________________________________________________________________________________________
activation_355 (Activation)      (None, None, None, 64 0           batch_normalization_110[0][0]    
____________________________________________________________________________________________________
conv2d_112 (Conv2D)              (None, None, None, 48 12288       mixed0[0][0]                     
____________________________________________________________________________________________________
conv2d_115 (Conv2D)              (None, None, None, 96 55296       activation_355[0][0]             
____________________________________________________________________________________________________
batch_normalization_108 (BatchNo (None, None, None, 48 144         conv2d_112[0][0]                 
____________________________________________________________________________________________________
batch_normalization_111 (BatchNo (None, None, None, 96 288         conv2d_115[0][0]                 
____________________________________________________________________________________________________
activation_353 (Activation)      (None, None, None, 48 0           batch_normalization_108[0][0]    
____________________________________________________________________________________________________
activation_356 (Activation)      (None, None, None, 96 0           batch_normalization_111[0][0]    
____________________________________________________________________________________________________
average_pooling2d_11 (AveragePoo (None, None, None, 25 0           mixed0[0][0]                     
____________________________________________________________________________________________________
conv2d_111 (Conv2D)              (None, None, None, 64 16384       mixed0[0][0]                     
____________________________________________________________________________________________________
conv2d_113 (Conv2D)              (None, None, None, 64 76800       activation_353[0][0]             
____________________________________________________________________________________________________
conv2d_116 (Conv2D)              (None, None, None, 96 82944       activation_356[0][0]             
____________________________________________________________________________________________________
conv2d_117 (Conv2D)              (None, None, None, 64 16384       average_pooling2d_11[0][0]       
____________________________________________________________________________________________________
batch_normalization_107 (BatchNo (None, None, None, 64 192         conv2d_111[0][0]                 
____________________________________________________________________________________________________
batch_normalization_109 (BatchNo (None, None, None, 64 192         conv2d_113[0][0]                 
____________________________________________________________________________________________________
batch_normalization_112 (BatchNo (None, None, None, 96 288         conv2d_116[0][0]                 
____________________________________________________________________________________________________
batch_normalization_113 (BatchNo (None, None, None, 64 192         conv2d_117[0][0]                 
____________________________________________________________________________________________________
activation_352 (Activation)      (None, None, None, 64 0           batch_normalization_107[0][0]    
____________________________________________________________________________________________________
activation_354 (Activation)      (None, None, None, 64 0           batch_normalization_109[0][0]    
____________________________________________________________________________________________________
activation_357 (Activation)      (None, None, None, 96 0           batch_normalization_112[0][0]    
____________________________________________________________________________________________________
activation_358 (Activation)      (None, None, None, 64 0           batch_normalization_113[0][0]    
____________________________________________________________________________________________________
mixed1 (Concatenate)             (None, None, None, 28 0           activation_352[0][0]             
                                                                   activation_354[0][0]             
                                                                   activation_357[0][0]             
                                                                   activation_358[0][0]             
____________________________________________________________________________________________________
conv2d_121 (Conv2D)              (None, None, None, 64 18432       mixed1[0][0]                     
____________________________________________________________________________________________________
batch_normalization_117 (BatchNo (None, None, None, 64 192         conv2d_121[0][0]                 
____________________________________________________________________________________________________
activation_362 (Activation)      (None, None, None, 64 0           batch_normalization_117[0][0]    
____________________________________________________________________________________________________
conv2d_119 (Conv2D)              (None, None, None, 48 13824       mixed1[0][0]                     
____________________________________________________________________________________________________
conv2d_122 (Conv2D)              (None, None, None, 96 55296       activation_362[0][0]             
____________________________________________________________________________________________________
batch_normalization_115 (BatchNo (None, None, None, 48 144         conv2d_119[0][0]                 
____________________________________________________________________________________________________
batch_normalization_118 (BatchNo (None, None, None, 96 288         conv2d_122[0][0]                 
____________________________________________________________________________________________________
activation_360 (Activation)      (None, None, None, 48 0           batch_normalization_115[0][0]    
____________________________________________________________________________________________________
activation_363 (Activation)      (None, None, None, 96 0           batch_normalization_118[0][0]    
____________________________________________________________________________________________________
average_pooling2d_12 (AveragePoo (None, None, None, 28 0           mixed1[0][0]                     
____________________________________________________________________________________________________
conv2d_118 (Conv2D)              (None, None, None, 64 18432       mixed1[0][0]                     
____________________________________________________________________________________________________
conv2d_120 (Conv2D)              (None, None, None, 64 76800       activation_360[0][0]             
____________________________________________________________________________________________________
conv2d_123 (Conv2D)              (None, None, None, 96 82944       activation_363[0][0]             
____________________________________________________________________________________________________
conv2d_124 (Conv2D)              (None, None, None, 64 18432       average_pooling2d_12[0][0]       
____________________________________________________________________________________________________
batch_normalization_114 (BatchNo (None, None, None, 64 192         conv2d_118[0][0]                 
____________________________________________________________________________________________________
batch_normalization_116 (BatchNo (None, None, None, 64 192         conv2d_120[0][0]                 
____________________________________________________________________________________________________
batch_normalization_119 (BatchNo (None, None, None, 96 288         conv2d_123[0][0]                 
____________________________________________________________________________________________________
batch_normalization_120 (BatchNo (None, None, None, 64 192         conv2d_124[0][0]                 
____________________________________________________________________________________________________
activation_359 (Activation)      (None, None, None, 64 0           batch_normalization_114[0][0]    
____________________________________________________________________________________________________
activation_361 (Activation)      (None, None, None, 64 0           batch_normalization_116[0][0]    
____________________________________________________________________________________________________
activation_364 (Activation)      (None, None, None, 96 0           batch_normalization_119[0][0]    
____________________________________________________________________________________________________
activation_365 (Activation)      (None, None, None, 64 0           batch_normalization_120[0][0]    
____________________________________________________________________________________________________
mixed2 (Concatenate)             (None, None, None, 28 0           activation_359[0][0]             
                                                                   activation_361[0][0]             
                                                                   activation_364[0][0]             
                                                                   activation_365[0][0]             
____________________________________________________________________________________________________
conv2d_126 (Conv2D)              (None, None, None, 64 18432       mixed2[0][0]                     
____________________________________________________________________________________________________
batch_normalization_122 (BatchNo (None, None, None, 64 192         conv2d_126[0][0]                 
____________________________________________________________________________________________________
activation_367 (Activation)      (None, None, None, 64 0           batch_normalization_122[0][0]    
____________________________________________________________________________________________________
conv2d_127 (Conv2D)              (None, None, None, 96 55296       activation_367[0][0]             
____________________________________________________________________________________________________
batch_normalization_123 (BatchNo (None, None, None, 96 288         conv2d_127[0][0]                 
____________________________________________________________________________________________________
activation_368 (Activation)      (None, None, None, 96 0           batch_normalization_123[0][0]    
____________________________________________________________________________________________________
conv2d_125 (Conv2D)              (None, None, None, 38 995328      mixed2[0][0]                     
____________________________________________________________________________________________________
conv2d_128 (Conv2D)              (None, None, None, 96 82944       activation_368[0][0]             
____________________________________________________________________________________________________
batch_normalization_121 (BatchNo (None, None, None, 38 1152        conv2d_125[0][0]                 
____________________________________________________________________________________________________
batch_normalization_124 (BatchNo (None, None, None, 96 288         conv2d_128[0][0]                 
____________________________________________________________________________________________________
activation_366 (Activation)      (None, None, None, 38 0           batch_normalization_121[0][0]    
____________________________________________________________________________________________________
activation_369 (Activation)      (None, None, None, 96 0           batch_normalization_124[0][0]    
____________________________________________________________________________________________________
max_pooling2d_14 (MaxPooling2D)  (None, None, None, 28 0           mixed2[0][0]                     
____________________________________________________________________________________________________
mixed3 (Concatenate)             (None, None, None, 76 0           activation_366[0][0]             
                                                                   activation_369[0][0]             
                                                                   max_pooling2d_14[0][0]           
____________________________________________________________________________________________________
conv2d_133 (Conv2D)              (None, None, None, 12 98304       mixed3[0][0]                     
____________________________________________________________________________________________________
batch_normalization_129 (BatchNo (None, None, None, 12 384         conv2d_133[0][0]                 
____________________________________________________________________________________________________
activation_374 (Activation)      (None, None, None, 12 0           batch_normalization_129[0][0]    
____________________________________________________________________________________________________
conv2d_134 (Conv2D)              (None, None, None, 12 114688      activation_374[0][0]             
____________________________________________________________________________________________________
batch_normalization_130 (BatchNo (None, None, None, 12 384         conv2d_134[0][0]                 
____________________________________________________________________________________________________
activation_375 (Activation)      (None, None, None, 12 0           batch_normalization_130[0][0]    
____________________________________________________________________________________________________
conv2d_130 (Conv2D)              (None, None, None, 12 98304       mixed3[0][0]                     
____________________________________________________________________________________________________
conv2d_135 (Conv2D)              (None, None, None, 12 114688      activation_375[0][0]             
____________________________________________________________________________________________________
batch_normalization_126 (BatchNo (None, None, None, 12 384         conv2d_130[0][0]                 
____________________________________________________________________________________________________
batch_normalization_131 (BatchNo (None, None, None, 12 384         conv2d_135[0][0]                 
____________________________________________________________________________________________________
activation_371 (Activation)      (None, None, None, 12 0           batch_normalization_126[0][0]    
____________________________________________________________________________________________________
activation_376 (Activation)      (None, None, None, 12 0           batch_normalization_131[0][0]    
____________________________________________________________________________________________________
conv2d_131 (Conv2D)              (None, None, None, 12 114688      activation_371[0][0]             
____________________________________________________________________________________________________
conv2d_136 (Conv2D)              (None, None, None, 12 114688      activation_376[0][0]             
____________________________________________________________________________________________________
batch_normalization_127 (BatchNo (None, None, None, 12 384         conv2d_131[0][0]                 
____________________________________________________________________________________________________
batch_normalization_132 (BatchNo (None, None, None, 12 384         conv2d_136[0][0]                 
____________________________________________________________________________________________________
activation_372 (Activation)      (None, None, None, 12 0           batch_normalization_127[0][0]    
____________________________________________________________________________________________________
activation_377 (Activation)      (None, None, None, 12 0           batch_normalization_132[0][0]    
____________________________________________________________________________________________________
average_pooling2d_13 (AveragePoo (None, None, None, 76 0           mixed3[0][0]                     
____________________________________________________________________________________________________
conv2d_129 (Conv2D)              (None, None, None, 19 147456      mixed3[0][0]                     
____________________________________________________________________________________________________
conv2d_132 (Conv2D)              (None, None, None, 19 172032      activation_372[0][0]             
____________________________________________________________________________________________________
conv2d_137 (Conv2D)              (None, None, None, 19 172032      activation_377[0][0]             
____________________________________________________________________________________________________
conv2d_138 (Conv2D)              (None, None, None, 19 147456      average_pooling2d_13[0][0]       
____________________________________________________________________________________________________
batch_normalization_125 (BatchNo (None, None, None, 19 576         conv2d_129[0][0]                 
____________________________________________________________________________________________________
batch_normalization_128 (BatchNo (None, None, None, 19 576         conv2d_132[0][0]                 
____________________________________________________________________________________________________
batch_normalization_133 (BatchNo (None, None, None, 19 576         conv2d_137[0][0]                 
____________________________________________________________________________________________________
batch_normalization_134 (BatchNo (None, None, None, 19 576         conv2d_138[0][0]                 
____________________________________________________________________________________________________
activation_370 (Activation)      (None, None, None, 19 0           batch_normalization_125[0][0]    
____________________________________________________________________________________________________
activation_373 (Activation)      (None, None, None, 19 0           batch_normalization_128[0][0]    
____________________________________________________________________________________________________
activation_378 (Activation)      (None, None, None, 19 0           batch_normalization_133[0][0]    
____________________________________________________________________________________________________
activation_379 (Activation)      (None, None, None, 19 0           batch_normalization_134[0][0]    
____________________________________________________________________________________________________
mixed4 (Concatenate)             (None, None, None, 76 0           activation_370[0][0]             
                                                                   activation_373[0][0]             
                                                                   activation_378[0][0]             
                                                                   activation_379[0][0]             
____________________________________________________________________________________________________
conv2d_143 (Conv2D)              (None, None, None, 16 122880      mixed4[0][0]                     
____________________________________________________________________________________________________
batch_normalization_139 (BatchNo (None, None, None, 16 480         conv2d_143[0][0]                 
____________________________________________________________________________________________________
activation_384 (Activation)      (None, None, None, 16 0           batch_normalization_139[0][0]    
____________________________________________________________________________________________________
conv2d_144 (Conv2D)              (None, None, None, 16 179200      activation_384[0][0]             
____________________________________________________________________________________________________
batch_normalization_140 (BatchNo (None, None, None, 16 480         conv2d_144[0][0]                 
____________________________________________________________________________________________________
activation_385 (Activation)      (None, None, None, 16 0           batch_normalization_140[0][0]    
____________________________________________________________________________________________________
conv2d_140 (Conv2D)              (None, None, None, 16 122880      mixed4[0][0]                     
____________________________________________________________________________________________________
conv2d_145 (Conv2D)              (None, None, None, 16 179200      activation_385[0][0]             
____________________________________________________________________________________________________
batch_normalization_136 (BatchNo (None, None, None, 16 480         conv2d_140[0][0]                 
____________________________________________________________________________________________________
batch_normalization_141 (BatchNo (None, None, None, 16 480         conv2d_145[0][0]                 
____________________________________________________________________________________________________
activation_381 (Activation)      (None, None, None, 16 0           batch_normalization_136[0][0]    
____________________________________________________________________________________________________
activation_386 (Activation)      (None, None, None, 16 0           batch_normalization_141[0][0]    
____________________________________________________________________________________________________
conv2d_141 (Conv2D)              (None, None, None, 16 179200      activation_381[0][0]             
____________________________________________________________________________________________________
conv2d_146 (Conv2D)              (None, None, None, 16 179200      activation_386[0][0]             
____________________________________________________________________________________________________
batch_normalization_137 (BatchNo (None, None, None, 16 480         conv2d_141[0][0]                 
____________________________________________________________________________________________________
batch_normalization_142 (BatchNo (None, None, None, 16 480         conv2d_146[0][0]                 
____________________________________________________________________________________________________
activation_382 (Activation)      (None, None, None, 16 0           batch_normalization_137[0][0]    
____________________________________________________________________________________________________
activation_387 (Activation)      (None, None, None, 16 0           batch_normalization_142[0][0]    
____________________________________________________________________________________________________
average_pooling2d_14 (AveragePoo (None, None, None, 76 0           mixed4[0][0]                     
____________________________________________________________________________________________________
conv2d_139 (Conv2D)              (None, None, None, 19 147456      mixed4[0][0]                     
____________________________________________________________________________________________________
conv2d_142 (Conv2D)              (None, None, None, 19 215040      activation_382[0][0]             
____________________________________________________________________________________________________
conv2d_147 (Conv2D)              (None, None, None, 19 215040      activation_387[0][0]             
____________________________________________________________________________________________________
conv2d_148 (Conv2D)              (None, None, None, 19 147456      average_pooling2d_14[0][0]       
____________________________________________________________________________________________________
batch_normalization_135 (BatchNo (None, None, None, 19 576         conv2d_139[0][0]                 
____________________________________________________________________________________________________
batch_normalization_138 (BatchNo (None, None, None, 19 576         conv2d_142[0][0]                 
____________________________________________________________________________________________________
batch_normalization_143 (BatchNo (None, None, None, 19 576         conv2d_147[0][0]                 
____________________________________________________________________________________________________
batch_normalization_144 (BatchNo (None, None, None, 19 576         conv2d_148[0][0]                 
____________________________________________________________________________________________________
activation_380 (Activation)      (None, None, None, 19 0           batch_normalization_135[0][0]    
____________________________________________________________________________________________________
activation_383 (Activation)      (None, None, None, 19 0           batch_normalization_138[0][0]    
____________________________________________________________________________________________________
activation_388 (Activation)      (None, None, None, 19 0           batch_normalization_143[0][0]    
____________________________________________________________________________________________________
activation_389 (Activation)      (None, None, None, 19 0           batch_normalization_144[0][0]    
____________________________________________________________________________________________________
mixed5 (Concatenate)             (None, None, None, 76 0           activation_380[0][0]             
                                                                   activation_383[0][0]             
                                                                   activation_388[0][0]             
                                                                   activation_389[0][0]             
____________________________________________________________________________________________________
conv2d_153 (Conv2D)              (None, None, None, 16 122880      mixed5[0][0]                     
____________________________________________________________________________________________________
batch_normalization_149 (BatchNo (None, None, None, 16 480         conv2d_153[0][0]                 
____________________________________________________________________________________________________
activation_394 (Activation)      (None, None, None, 16 0           batch_normalization_149[0][0]    
____________________________________________________________________________________________________
conv2d_154 (Conv2D)              (None, None, None, 16 179200      activation_394[0][0]             
____________________________________________________________________________________________________
batch_normalization_150 (BatchNo (None, None, None, 16 480         conv2d_154[0][0]                 
____________________________________________________________________________________________________
activation_395 (Activation)      (None, None, None, 16 0           batch_normalization_150[0][0]    
____________________________________________________________________________________________________
conv2d_150 (Conv2D)              (None, None, None, 16 122880      mixed5[0][0]                     
____________________________________________________________________________________________________
conv2d_155 (Conv2D)              (None, None, None, 16 179200      activation_395[0][0]             
____________________________________________________________________________________________________
batch_normalization_146 (BatchNo (None, None, None, 16 480         conv2d_150[0][0]                 
____________________________________________________________________________________________________
batch_normalization_151 (BatchNo (None, None, None, 16 480         conv2d_155[0][0]                 
____________________________________________________________________________________________________
activation_391 (Activation)      (None, None, None, 16 0           batch_normalization_146[0][0]    
____________________________________________________________________________________________________
activation_396 (Activation)      (None, None, None, 16 0           batch_normalization_151[0][0]    
____________________________________________________________________________________________________
conv2d_151 (Conv2D)              (None, None, None, 16 179200      activation_391[0][0]             
____________________________________________________________________________________________________
conv2d_156 (Conv2D)              (None, None, None, 16 179200      activation_396[0][0]             
____________________________________________________________________________________________________
batch_normalization_147 (BatchNo (None, None, None, 16 480         conv2d_151[0][0]                 
____________________________________________________________________________________________________
batch_normalization_152 (BatchNo (None, None, None, 16 480         conv2d_156[0][0]                 
____________________________________________________________________________________________________
activation_392 (Activation)      (None, None, None, 16 0           batch_normalization_147[0][0]    
____________________________________________________________________________________________________
activation_397 (Activation)      (None, None, None, 16 0           batch_normalization_152[0][0]    
____________________________________________________________________________________________________
average_pooling2d_15 (AveragePoo (None, None, None, 76 0           mixed5[0][0]                     
____________________________________________________________________________________________________
conv2d_149 (Conv2D)              (None, None, None, 19 147456      mixed5[0][0]                     
____________________________________________________________________________________________________
conv2d_152 (Conv2D)              (None, None, None, 19 215040      activation_392[0][0]             
____________________________________________________________________________________________________
conv2d_157 (Conv2D)              (None, None, None, 19 215040      activation_397[0][0]             
____________________________________________________________________________________________________
conv2d_158 (Conv2D)              (None, None, None, 19 147456      average_pooling2d_15[0][0]       
____________________________________________________________________________________________________
batch_normalization_145 (BatchNo (None, None, None, 19 576         conv2d_149[0][0]                 
____________________________________________________________________________________________________
batch_normalization_148 (BatchNo (None, None, None, 19 576         conv2d_152[0][0]                 
____________________________________________________________________________________________________
batch_normalization_153 (BatchNo (None, None, None, 19 576         conv2d_157[0][0]                 
____________________________________________________________________________________________________
batch_normalization_154 (BatchNo (None, None, None, 19 576         conv2d_158[0][0]                 
____________________________________________________________________________________________________
activation_390 (Activation)      (None, None, None, 19 0           batch_normalization_145[0][0]    
____________________________________________________________________________________________________
activation_393 (Activation)      (None, None, None, 19 0           batch_normalization_148[0][0]    
____________________________________________________________________________________________________
activation_398 (Activation)      (None, None, None, 19 0           batch_normalization_153[0][0]    
____________________________________________________________________________________________________
activation_399 (Activation)      (None, None, None, 19 0           batch_normalization_154[0][0]    
____________________________________________________________________________________________________
mixed6 (Concatenate)             (None, None, None, 76 0           activation_390[0][0]             
                                                                   activation_393[0][0]             
                                                                   activation_398[0][0]             
                                                                   activation_399[0][0]             
____________________________________________________________________________________________________
conv2d_163 (Conv2D)              (None, None, None, 19 147456      mixed6[0][0]                     
____________________________________________________________________________________________________
batch_normalization_159 (BatchNo (None, None, None, 19 576         conv2d_163[0][0]                 
____________________________________________________________________________________________________
activation_404 (Activation)      (None, None, None, 19 0           batch_normalization_159[0][0]    
____________________________________________________________________________________________________
conv2d_164 (Conv2D)              (None, None, None, 19 258048      activation_404[0][0]             
____________________________________________________________________________________________________
batch_normalization_160 (BatchNo (None, None, None, 19 576         conv2d_164[0][0]                 
____________________________________________________________________________________________________
activation_405 (Activation)      (None, None, None, 19 0           batch_normalization_160[0][0]    
____________________________________________________________________________________________________
conv2d_160 (Conv2D)              (None, None, None, 19 147456      mixed6[0][0]                     
____________________________________________________________________________________________________
conv2d_165 (Conv2D)              (None, None, None, 19 258048      activation_405[0][0]             
____________________________________________________________________________________________________
batch_normalization_156 (BatchNo (None, None, None, 19 576         conv2d_160[0][0]                 
____________________________________________________________________________________________________
batch_normalization_161 (BatchNo (None, None, None, 19 576         conv2d_165[0][0]                 
____________________________________________________________________________________________________
activation_401 (Activation)      (None, None, None, 19 0           batch_normalization_156[0][0]    
____________________________________________________________________________________________________
activation_406 (Activation)      (None, None, None, 19 0           batch_normalization_161[0][0]    
____________________________________________________________________________________________________
conv2d_161 (Conv2D)              (None, None, None, 19 258048      activation_401[0][0]             
____________________________________________________________________________________________________
conv2d_166 (Conv2D)              (None, None, None, 19 258048      activation_406[0][0]             
____________________________________________________________________________________________________
batch_normalization_157 (BatchNo (None, None, None, 19 576         conv2d_161[0][0]                 
____________________________________________________________________________________________________
batch_normalization_162 (BatchNo (None, None, None, 19 576         conv2d_166[0][0]                 
____________________________________________________________________________________________________
activation_402 (Activation)      (None, None, None, 19 0           batch_normalization_157[0][0]    
____________________________________________________________________________________________________
activation_407 (Activation)      (None, None, None, 19 0           batch_normalization_162[0][0]    
____________________________________________________________________________________________________
average_pooling2d_16 (AveragePoo (None, None, None, 76 0           mixed6[0][0]                     
____________________________________________________________________________________________________
conv2d_159 (Conv2D)              (None, None, None, 19 147456      mixed6[0][0]                     
____________________________________________________________________________________________________
conv2d_162 (Conv2D)              (None, None, None, 19 258048      activation_402[0][0]             
____________________________________________________________________________________________________
conv2d_167 (Conv2D)              (None, None, None, 19 258048      activation_407[0][0]             
____________________________________________________________________________________________________
conv2d_168 (Conv2D)              (None, None, None, 19 147456      average_pooling2d_16[0][0]       
____________________________________________________________________________________________________
batch_normalization_155 (BatchNo (None, None, None, 19 576         conv2d_159[0][0]                 
____________________________________________________________________________________________________
batch_normalization_158 (BatchNo (None, None, None, 19 576         conv2d_162[0][0]                 
____________________________________________________________________________________________________
batch_normalization_163 (BatchNo (None, None, None, 19 576         conv2d_167[0][0]                 
____________________________________________________________________________________________________
batch_normalization_164 (BatchNo (None, None, None, 19 576         conv2d_168[0][0]                 
____________________________________________________________________________________________________
activation_400 (Activation)      (None, None, None, 19 0           batch_normalization_155[0][0]    
____________________________________________________________________________________________________
activation_403 (Activation)      (None, None, None, 19 0           batch_normalization_158[0][0]    
____________________________________________________________________________________________________
activation_408 (Activation)      (None, None, None, 19 0           batch_normalization_163[0][0]    
____________________________________________________________________________________________________
activation_409 (Activation)      (None, None, None, 19 0           batch_normalization_164[0][0]    
____________________________________________________________________________________________________
mixed7 (Concatenate)             (None, None, None, 76 0           activation_400[0][0]             
                                                                   activation_403[0][0]             
                                                                   activation_408[0][0]             
                                                                   activation_409[0][0]             
____________________________________________________________________________________________________
conv2d_171 (Conv2D)              (None, None, None, 19 147456      mixed7[0][0]                     
____________________________________________________________________________________________________
batch_normalization_167 (BatchNo (None, None, None, 19 576         conv2d_171[0][0]                 
____________________________________________________________________________________________________
activation_412 (Activation)      (None, None, None, 19 0           batch_normalization_167[0][0]    
____________________________________________________________________________________________________
conv2d_172 (Conv2D)              (None, None, None, 19 258048      activation_412[0][0]             
____________________________________________________________________________________________________
batch_normalization_168 (BatchNo (None, None, None, 19 576         conv2d_172[0][0]                 
____________________________________________________________________________________________________
activation_413 (Activation)      (None, None, None, 19 0           batch_normalization_168[0][0]    
____________________________________________________________________________________________________
conv2d_169 (Conv2D)              (None, None, None, 19 147456      mixed7[0][0]                     
____________________________________________________________________________________________________
conv2d_173 (Conv2D)              (None, None, None, 19 258048      activation_413[0][0]             
____________________________________________________________________________________________________
batch_normalization_165 (BatchNo (None, None, None, 19 576         conv2d_169[0][0]                 
____________________________________________________________________________________________________
batch_normalization_169 (BatchNo (None, None, None, 19 576         conv2d_173[0][0]                 
____________________________________________________________________________________________________
activation_410 (Activation)      (None, None, None, 19 0           batch_normalization_165[0][0]    
____________________________________________________________________________________________________
activation_414 (Activation)      (None, None, None, 19 0           batch_normalization_169[0][0]    
____________________________________________________________________________________________________
conv2d_170 (Conv2D)              (None, None, None, 32 552960      activation_410[0][0]             
____________________________________________________________________________________________________
conv2d_174 (Conv2D)              (None, None, None, 19 331776      activation_414[0][0]             
____________________________________________________________________________________________________
batch_normalization_166 (BatchNo (None, None, None, 32 960         conv2d_170[0][0]                 
____________________________________________________________________________________________________
batch_normalization_170 (BatchNo (None, None, None, 19 576         conv2d_174[0][0]                 
____________________________________________________________________________________________________
activation_411 (Activation)      (None, None, None, 32 0           batch_normalization_166[0][0]    
____________________________________________________________________________________________________
activation_415 (Activation)      (None, None, None, 19 0           batch_normalization_170[0][0]    
____________________________________________________________________________________________________
max_pooling2d_15 (MaxPooling2D)  (None, None, None, 76 0           mixed7[0][0]                     
____________________________________________________________________________________________________
mixed8 (Concatenate)             (None, None, None, 12 0           activation_411[0][0]             
                                                                   activation_415[0][0]             
                                                                   max_pooling2d_15[0][0]           
____________________________________________________________________________________________________
conv2d_179 (Conv2D)              (None, None, None, 44 573440      mixed8[0][0]                     
____________________________________________________________________________________________________
batch_normalization_175 (BatchNo (None, None, None, 44 1344        conv2d_179[0][0]                 
____________________________________________________________________________________________________
activation_420 (Activation)      (None, None, None, 44 0           batch_normalization_175[0][0]    
____________________________________________________________________________________________________
conv2d_176 (Conv2D)              (None, None, None, 38 491520      mixed8[0][0]                     
____________________________________________________________________________________________________
conv2d_180 (Conv2D)              (None, None, None, 38 1548288     activation_420[0][0]             
____________________________________________________________________________________________________
batch_normalization_172 (BatchNo (None, None, None, 38 1152        conv2d_176[0][0]                 
____________________________________________________________________________________________________
batch_normalization_176 (BatchNo (None, None, None, 38 1152        conv2d_180[0][0]                 
____________________________________________________________________________________________________
activation_417 (Activation)      (None, None, None, 38 0           batch_normalization_172[0][0]    
____________________________________________________________________________________________________
activation_421 (Activation)      (None, None, None, 38 0           batch_normalization_176[0][0]    
____________________________________________________________________________________________________
conv2d_177 (Conv2D)              (None, None, None, 38 442368      activation_417[0][0]             
____________________________________________________________________________________________________
conv2d_178 (Conv2D)              (None, None, None, 38 442368      activation_417[0][0]             
____________________________________________________________________________________________________
conv2d_181 (Conv2D)              (None, None, None, 38 442368      activation_421[0][0]             
____________________________________________________________________________________________________
conv2d_182 (Conv2D)              (None, None, None, 38 442368      activation_421[0][0]             
____________________________________________________________________________________________________
average_pooling2d_17 (AveragePoo (None, None, None, 12 0           mixed8[0][0]                     
____________________________________________________________________________________________________
conv2d_175 (Conv2D)              (None, None, None, 32 409600      mixed8[0][0]                     
____________________________________________________________________________________________________
batch_normalization_173 (BatchNo (None, None, None, 38 1152        conv2d_177[0][0]                 
____________________________________________________________________________________________________
batch_normalization_174 (BatchNo (None, None, None, 38 1152        conv2d_178[0][0]                 
____________________________________________________________________________________________________
batch_normalization_177 (BatchNo (None, None, None, 38 1152        conv2d_181[0][0]                 
____________________________________________________________________________________________________
batch_normalization_178 (BatchNo (None, None, None, 38 1152        conv2d_182[0][0]                 
____________________________________________________________________________________________________
conv2d_183 (Conv2D)              (None, None, None, 19 245760      average_pooling2d_17[0][0]       
____________________________________________________________________________________________________
batch_normalization_171 (BatchNo (None, None, None, 32 960         conv2d_175[0][0]                 
____________________________________________________________________________________________________
activation_418 (Activation)      (None, None, None, 38 0           batch_normalization_173[0][0]    
____________________________________________________________________________________________________
activation_419 (Activation)      (None, None, None, 38 0           batch_normalization_174[0][0]    
____________________________________________________________________________________________________
activation_422 (Activation)      (None, None, None, 38 0           batch_normalization_177[0][0]    
____________________________________________________________________________________________________
activation_423 (Activation)      (None, None, None, 38 0           batch_normalization_178[0][0]    
____________________________________________________________________________________________________
batch_normalization_179 (BatchNo (None, None, None, 19 576         conv2d_183[0][0]                 
____________________________________________________________________________________________________
activation_416 (Activation)      (None, None, None, 32 0           batch_normalization_171[0][0]    
____________________________________________________________________________________________________
mixed9_0 (Concatenate)           (None, None, None, 76 0           activation_418[0][0]             
                                                                   activation_419[0][0]             
____________________________________________________________________________________________________
concatenate_3 (Concatenate)      (None, None, None, 76 0           activation_422[0][0]             
                                                                   activation_423[0][0]             
____________________________________________________________________________________________________
activation_424 (Activation)      (None, None, None, 19 0           batch_normalization_179[0][0]    
____________________________________________________________________________________________________
mixed9 (Concatenate)             (None, None, None, 20 0           activation_416[0][0]             
                                                                   mixed9_0[0][0]                   
                                                                   concatenate_3[0][0]              
                                                                   activation_424[0][0]             
____________________________________________________________________________________________________
conv2d_188 (Conv2D)              (None, None, None, 44 917504      mixed9[0][0]                     
____________________________________________________________________________________________________
batch_normalization_184 (BatchNo (None, None, None, 44 1344        conv2d_188[0][0]                 
____________________________________________________________________________________________________
activation_429 (Activation)      (None, None, None, 44 0           batch_normalization_184[0][0]    
____________________________________________________________________________________________________
conv2d_185 (Conv2D)              (None, None, None, 38 786432      mixed9[0][0]                     
____________________________________________________________________________________________________
conv2d_189 (Conv2D)              (None, None, None, 38 1548288     activation_429[0][0]             
____________________________________________________________________________________________________
batch_normalization_181 (BatchNo (None, None, None, 38 1152        conv2d_185[0][0]                 
____________________________________________________________________________________________________
batch_normalization_185 (BatchNo (None, None, None, 38 1152        conv2d_189[0][0]                 
____________________________________________________________________________________________________
activation_426 (Activation)      (None, None, None, 38 0           batch_normalization_181[0][0]    
____________________________________________________________________________________________________
activation_430 (Activation)      (None, None, None, 38 0           batch_normalization_185[0][0]    
____________________________________________________________________________________________________
conv2d_186 (Conv2D)              (None, None, None, 38 442368      activation_426[0][0]             
____________________________________________________________________________________________________
conv2d_187 (Conv2D)              (None, None, None, 38 442368      activation_426[0][0]             
____________________________________________________________________________________________________
conv2d_190 (Conv2D)              (None, None, None, 38 442368      activation_430[0][0]             
____________________________________________________________________________________________________
conv2d_191 (Conv2D)              (None, None, None, 38 442368      activation_430[0][0]             
____________________________________________________________________________________________________
average_pooling2d_18 (AveragePoo (None, None, None, 20 0           mixed9[0][0]                     
____________________________________________________________________________________________________
conv2d_184 (Conv2D)              (None, None, None, 32 655360      mixed9[0][0]                     
____________________________________________________________________________________________________
batch_normalization_182 (BatchNo (None, None, None, 38 1152        conv2d_186[0][0]                 
____________________________________________________________________________________________________
batch_normalization_183 (BatchNo (None, None, None, 38 1152        conv2d_187[0][0]                 
____________________________________________________________________________________________________
batch_normalization_186 (BatchNo (None, None, None, 38 1152        conv2d_190[0][0]                 
____________________________________________________________________________________________________
batch_normalization_187 (BatchNo (None, None, None, 38 1152        conv2d_191[0][0]                 
____________________________________________________________________________________________________
conv2d_192 (Conv2D)              (None, None, None, 19 393216      average_pooling2d_18[0][0]       
____________________________________________________________________________________________________
batch_normalization_180 (BatchNo (None, None, None, 32 960         conv2d_184[0][0]                 
____________________________________________________________________________________________________
activation_427 (Activation)      (None, None, None, 38 0           batch_normalization_182[0][0]    
____________________________________________________________________________________________________
activation_428 (Activation)      (None, None, None, 38 0           batch_normalization_183[0][0]    
____________________________________________________________________________________________________
activation_431 (Activation)      (None, None, None, 38 0           batch_normalization_186[0][0]    
____________________________________________________________________________________________________
activation_432 (Activation)      (None, None, None, 38 0           batch_normalization_187[0][0]    
____________________________________________________________________________________________________
batch_normalization_188 (BatchNo (None, None, None, 19 576         conv2d_192[0][0]                 
____________________________________________________________________________________________________
activation_425 (Activation)      (None, None, None, 32 0           batch_normalization_180[0][0]    
____________________________________________________________________________________________________
mixed9_1 (Concatenate)           (None, None, None, 76 0           activation_427[0][0]             
                                                                   activation_428[0][0]             
____________________________________________________________________________________________________
concatenate_4 (Concatenate)      (None, None, None, 76 0           activation_431[0][0]             
                                                                   activation_432[0][0]             
____________________________________________________________________________________________________
activation_433 (Activation)      (None, None, None, 19 0           batch_normalization_188[0][0]    
____________________________________________________________________________________________________
mixed10 (Concatenate)            (None, None, None, 20 0           activation_425[0][0]             
                                                                   mixed9_1[0][0]                   
                                                                   concatenate_4[0][0]              
                                                                   activation_433[0][0]             
____________________________________________________________________________________________________
global_average_pooling2d_7 (Glob (None, 2048)          0           mixed10[0][0]                    
____________________________________________________________________________________________________
dense_11 (Dense)                 (None, 133)           272517      global_average_pooling2d_7[0][0] 
====================================================================================================
Total params: 22,075,301
Trainable params: 272,517
Non-trainable params: 21,802,784
____________________________________________________________________________________________________
In [47]:
steps = math.ceil(train_tensors.shape[0]/batch_size)
validation_steps = math.ceil(valid_tensors.shape[0]/batch_size)
print('Training Samples: {} Validation Samples: {} Batch Size: {} Steps: {}'.format(
      train_tensors.shape[0], valid_tensors.shape[0], batch_size, steps))

epochs = 20
epochtimer = EpochTimer()

hist = finetune_model.fit_generator(
    train_generator,
    validation_data=validation_generator,
    epochs=epochs,
    steps_per_epoch=steps,
    validation_steps=validation_steps,
    callbacks=[epochtimer])

show_history_graph(hist)

top_model_file = 'saved_models/weights.best.{}.hdf5'.format('inceptionv3_top')
finetune_model.save(top_model_file)
Training Samples: 6680 Validation Samples: 835 Batch Size: 100 Steps: 67
Epoch 1/20
66/67 [============================>.] - ETA: 2s - loss: 3.1259 - acc: 0.4227Epoch 0 took 178.1432847420001 seconds
67/67 [==============================] - 178s - loss: 3.1037 - acc: 0.4267 - val_loss: 1.3809 - val_acc: 0.7305
Epoch 2/20
66/67 [============================>.] - ETA: 1s - loss: 1.2612 - acc: 0.7201Epoch 1 took 153.75359839700104 seconds
67/67 [==============================] - 153s - loss: 1.2587 - acc: 0.7203 - val_loss: 0.9168 - val_acc: 0.7701
Epoch 3/20
66/67 [============================>.] - ETA: 1s - loss: 0.8893 - acc: 0.7838Epoch 2 took 154.34958850400108 seconds
67/67 [==============================] - 154s - loss: 0.8916 - acc: 0.7831 - val_loss: 0.8153 - val_acc: 0.7784
Epoch 4/20
66/67 [============================>.] - ETA: 1s - loss: 0.7561 - acc: 0.8060Epoch 3 took 152.70911943399915 seconds
67/67 [==============================] - 152s - loss: 0.7584 - acc: 0.8055 - val_loss: 0.7768 - val_acc: 0.7796
Epoch 5/20
66/67 [============================>.] - ETA: 1s - loss: 0.6627 - acc: 0.8265Epoch 4 took 153.64200245699976 seconds
67/67 [==============================] - 153s - loss: 0.6605 - acc: 0.8272 - val_loss: 0.7186 - val_acc: 0.7964
Epoch 6/20
66/67 [============================>.] - ETA: 1s - loss: 0.5962 - acc: 0.8409Epoch 5 took 153.9223850669987 seconds
67/67 [==============================] - 153s - loss: 0.5982 - acc: 0.8403 - val_loss: 0.7230 - val_acc: 0.8048
Epoch 7/20
66/67 [============================>.] - ETA: 1s - loss: 0.5472 - acc: 0.8484Epoch 6 took 154.76483597900005 seconds
67/67 [==============================] - 154s - loss: 0.5476 - acc: 0.8483 - val_loss: 0.7634 - val_acc: 0.7665
Epoch 8/20
66/67 [============================>.] - ETA: 1s - loss: 0.5073 - acc: 0.8626Epoch 7 took 154.23233074199925 seconds
67/67 [==============================] - 154s - loss: 0.5063 - acc: 0.8630 - val_loss: 0.7220 - val_acc: 0.7964
Epoch 9/20
66/67 [============================>.] - ETA: 1s - loss: 0.4657 - acc: 0.8723Epoch 8 took 156.53892154099958 seconds
67/67 [==============================] - 156s - loss: 0.4652 - acc: 0.8720 - val_loss: 0.6767 - val_acc: 0.8012
Epoch 10/20
66/67 [============================>.] - ETA: 1s - loss: 0.4541 - acc: 0.8691Epoch 9 took 153.08089096299955 seconds
67/67 [==============================] - 153s - loss: 0.4550 - acc: 0.8690 - val_loss: 0.6572 - val_acc: 0.8024
Epoch 11/20
66/67 [============================>.] - ETA: 1s - loss: 0.4202 - acc: 0.8791Epoch 10 took 155.0555329910003 seconds
67/67 [==============================] - 155s - loss: 0.4196 - acc: 0.8792 - val_loss: 0.6364 - val_acc: 0.7952
Epoch 12/20
66/67 [============================>.] - ETA: 1s - loss: 0.3882 - acc: 0.8910Epoch 11 took 153.35859020299904 seconds
67/67 [==============================] - 153s - loss: 0.3889 - acc: 0.8904 - val_loss: 0.7036 - val_acc: 0.7880
Epoch 13/20
66/67 [============================>.] - ETA: 1s - loss: 0.3757 - acc: 0.8904Epoch 12 took 154.63203400900056 seconds
67/67 [==============================] - 154s - loss: 0.3747 - acc: 0.8907 - val_loss: 0.6716 - val_acc: 0.7976
Epoch 14/20
66/67 [============================>.] - ETA: 1s - loss: 0.3673 - acc: 0.8992Epoch 13 took 153.45572698600154 seconds
67/67 [==============================] - 153s - loss: 0.3676 - acc: 0.8990 - val_loss: 0.6175 - val_acc: 0.8156
Epoch 15/20
66/67 [============================>.] - ETA: 1s - loss: 0.3635 - acc: 0.8970Epoch 14 took 153.5305975680003 seconds
67/67 [==============================] - 153s - loss: 0.3630 - acc: 0.8974 - val_loss: 0.6928 - val_acc: 0.7880
Epoch 16/20
66/67 [============================>.] - ETA: 1s - loss: 0.3291 - acc: 0.9063Epoch 15 took 151.87741277900022 seconds
67/67 [==============================] - 151s - loss: 0.3289 - acc: 0.9065 - val_loss: 0.6048 - val_acc: 0.8204
Epoch 17/20
66/67 [============================>.] - ETA: 1s - loss: 0.3311 - acc: 0.9051Epoch 16 took 154.83815087400035 seconds
67/67 [==============================] - 154s - loss: 0.3340 - acc: 0.9044 - val_loss: 0.6130 - val_acc: 0.8204
Epoch 18/20
66/67 [============================>.] - ETA: 1s - loss: 0.3142 - acc: 0.9107Epoch 17 took 152.38418889999957 seconds
67/67 [==============================] - 152s - loss: 0.3141 - acc: 0.9107 - val_loss: 0.6780 - val_acc: 0.8144
Epoch 19/20
66/67 [============================>.] - ETA: 1s - loss: 0.3006 - acc: 0.9136Epoch 18 took 153.5867456979995 seconds
67/67 [==============================] - 153s - loss: 0.2991 - acc: 0.9140 - val_loss: 0.6487 - val_acc: 0.8072
Epoch 20/20
66/67 [============================>.] - ETA: 1s - loss: 0.3023 - acc: 0.9132Epoch 19 took 152.5227831459997 seconds
67/67 [==============================] - 152s - loss: 0.3001 - acc: 0.9141 - val_loss: 0.5991 - val_acc: 0.8204
Training took 3101.1852011249994 seconds
In [48]:
predictions = [np.argmax(finetune_model.predict(np.expand_dims(feature, axis=0))) for feature in inception_test_tensors]

# report test accuracy
test_accuracy = 100*np.sum(np.array(predictions)==np.argmax(test_targets, axis=1))/len(predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 85.8852%
In [50]:
from keras.optimizers import SGD

# NB_IV3_LAYERS corresponds to the top 2 inception blocks in the inceptionv3 architecture
# Those should be finetuned.
NB_IV3_LAYERS_TO_FREEZE = 172
for layer in finetune_model.layers[:NB_IV3_LAYERS_TO_FREEZE]:
    layer.trainable = False
for layer in finetune_model.layers[NB_IV3_LAYERS_TO_FREEZE:]:
    layer.trainable = True

finetune_model.summary()

# Use a slow stable learning method to prevent introducing bad noise into the lower layers
finetune_model.compile(optimizer=SGD(lr=0.0001, momentum=0.9), loss='categorical_crossentropy', metrics=['accuracy'])
____________________________________________________________________________________________________
Layer (type)                     Output Shape          Param #     Connected to                     
====================================================================================================
input_7 (InputLayer)             (None, None, None, 3) 0                                            
____________________________________________________________________________________________________
conv2d_99 (Conv2D)               (None, None, None, 32 864         input_7[0][0]                    
____________________________________________________________________________________________________
batch_normalization_95 (BatchNor (None, None, None, 32 96          conv2d_99[0][0]                  
____________________________________________________________________________________________________
activation_340 (Activation)      (None, None, None, 32 0           batch_normalization_95[0][0]     
____________________________________________________________________________________________________
conv2d_100 (Conv2D)              (None, None, None, 32 9216        activation_340[0][0]             
____________________________________________________________________________________________________
batch_normalization_96 (BatchNor (None, None, None, 32 96          conv2d_100[0][0]                 
____________________________________________________________________________________________________
activation_341 (Activation)      (None, None, None, 32 0           batch_normalization_96[0][0]     
____________________________________________________________________________________________________
conv2d_101 (Conv2D)              (None, None, None, 64 18432       activation_341[0][0]             
____________________________________________________________________________________________________
batch_normalization_97 (BatchNor (None, None, None, 64 192         conv2d_101[0][0]                 
____________________________________________________________________________________________________
activation_342 (Activation)      (None, None, None, 64 0           batch_normalization_97[0][0]     
____________________________________________________________________________________________________
max_pooling2d_12 (MaxPooling2D)  (None, None, None, 64 0           activation_342[0][0]             
____________________________________________________________________________________________________
conv2d_102 (Conv2D)              (None, None, None, 80 5120        max_pooling2d_12[0][0]           
____________________________________________________________________________________________________
batch_normalization_98 (BatchNor (None, None, None, 80 240         conv2d_102[0][0]                 
____________________________________________________________________________________________________
activation_343 (Activation)      (None, None, None, 80 0           batch_normalization_98[0][0]     
____________________________________________________________________________________________________
conv2d_103 (Conv2D)              (None, None, None, 19 138240      activation_343[0][0]             
____________________________________________________________________________________________________
batch_normalization_99 (BatchNor (None, None, None, 19 576         conv2d_103[0][0]                 
____________________________________________________________________________________________________
activation_344 (Activation)      (None, None, None, 19 0           batch_normalization_99[0][0]     
____________________________________________________________________________________________________
max_pooling2d_13 (MaxPooling2D)  (None, None, None, 19 0           activation_344[0][0]             
____________________________________________________________________________________________________
conv2d_107 (Conv2D)              (None, None, None, 64 12288       max_pooling2d_13[0][0]           
____________________________________________________________________________________________________
batch_normalization_103 (BatchNo (None, None, None, 64 192         conv2d_107[0][0]                 
____________________________________________________________________________________________________
activation_348 (Activation)      (None, None, None, 64 0           batch_normalization_103[0][0]    
____________________________________________________________________________________________________
conv2d_105 (Conv2D)              (None, None, None, 48 9216        max_pooling2d_13[0][0]           
____________________________________________________________________________________________________
conv2d_108 (Conv2D)              (None, None, None, 96 55296       activation_348[0][0]             
____________________________________________________________________________________________________
batch_normalization_101 (BatchNo (None, None, None, 48 144         conv2d_105[0][0]                 
____________________________________________________________________________________________________
batch_normalization_104 (BatchNo (None, None, None, 96 288         conv2d_108[0][0]                 
____________________________________________________________________________________________________
activation_346 (Activation)      (None, None, None, 48 0           batch_normalization_101[0][0]    
____________________________________________________________________________________________________
activation_349 (Activation)      (None, None, None, 96 0           batch_normalization_104[0][0]    
____________________________________________________________________________________________________
average_pooling2d_10 (AveragePoo (None, None, None, 19 0           max_pooling2d_13[0][0]           
____________________________________________________________________________________________________
conv2d_104 (Conv2D)              (None, None, None, 64 12288       max_pooling2d_13[0][0]           
____________________________________________________________________________________________________
conv2d_106 (Conv2D)              (None, None, None, 64 76800       activation_346[0][0]             
____________________________________________________________________________________________________
conv2d_109 (Conv2D)              (None, None, None, 96 82944       activation_349[0][0]             
____________________________________________________________________________________________________
conv2d_110 (Conv2D)              (None, None, None, 32 6144        average_pooling2d_10[0][0]       
____________________________________________________________________________________________________
batch_normalization_100 (BatchNo (None, None, None, 64 192         conv2d_104[0][0]                 
____________________________________________________________________________________________________
batch_normalization_102 (BatchNo (None, None, None, 64 192         conv2d_106[0][0]                 
____________________________________________________________________________________________________
batch_normalization_105 (BatchNo (None, None, None, 96 288         conv2d_109[0][0]                 
____________________________________________________________________________________________________
batch_normalization_106 (BatchNo (None, None, None, 32 96          conv2d_110[0][0]                 
____________________________________________________________________________________________________
activation_345 (Activation)      (None, None, None, 64 0           batch_normalization_100[0][0]    
____________________________________________________________________________________________________
activation_347 (Activation)      (None, None, None, 64 0           batch_normalization_102[0][0]    
____________________________________________________________________________________________________
activation_350 (Activation)      (None, None, None, 96 0           batch_normalization_105[0][0]    
____________________________________________________________________________________________________
activation_351 (Activation)      (None, None, None, 32 0           batch_normalization_106[0][0]    
____________________________________________________________________________________________________
mixed0 (Concatenate)             (None, None, None, 25 0           activation_345[0][0]             
                                                                   activation_347[0][0]             
                                                                   activation_350[0][0]             
                                                                   activation_351[0][0]             
____________________________________________________________________________________________________
conv2d_114 (Conv2D)              (None, None, None, 64 16384       mixed0[0][0]                     
____________________________________________________________________________________________________
batch_normalization_110 (BatchNo (None, None, None, 64 192         conv2d_114[0][0]                 
____________________________________________________________________________________________________
activation_355 (Activation)      (None, None, None, 64 0           batch_normalization_110[0][0]    
____________________________________________________________________________________________________
conv2d_112 (Conv2D)              (None, None, None, 48 12288       mixed0[0][0]                     
____________________________________________________________________________________________________
conv2d_115 (Conv2D)              (None, None, None, 96 55296       activation_355[0][0]             
____________________________________________________________________________________________________
batch_normalization_108 (BatchNo (None, None, None, 48 144         conv2d_112[0][0]                 
____________________________________________________________________________________________________
batch_normalization_111 (BatchNo (None, None, None, 96 288         conv2d_115[0][0]                 
____________________________________________________________________________________________________
activation_353 (Activation)      (None, None, None, 48 0           batch_normalization_108[0][0]    
____________________________________________________________________________________________________
activation_356 (Activation)      (None, None, None, 96 0           batch_normalization_111[0][0]    
____________________________________________________________________________________________________
average_pooling2d_11 (AveragePoo (None, None, None, 25 0           mixed0[0][0]                     
____________________________________________________________________________________________________
conv2d_111 (Conv2D)              (None, None, None, 64 16384       mixed0[0][0]                     
____________________________________________________________________________________________________
conv2d_113 (Conv2D)              (None, None, None, 64 76800       activation_353[0][0]             
____________________________________________________________________________________________________
conv2d_116 (Conv2D)              (None, None, None, 96 82944       activation_356[0][0]             
____________________________________________________________________________________________________
conv2d_117 (Conv2D)              (None, None, None, 64 16384       average_pooling2d_11[0][0]       
____________________________________________________________________________________________________
batch_normalization_107 (BatchNo (None, None, None, 64 192         conv2d_111[0][0]                 
____________________________________________________________________________________________________
batch_normalization_109 (BatchNo (None, None, None, 64 192         conv2d_113[0][0]                 
____________________________________________________________________________________________________
batch_normalization_112 (BatchNo (None, None, None, 96 288         conv2d_116[0][0]                 
____________________________________________________________________________________________________
batch_normalization_113 (BatchNo (None, None, None, 64 192         conv2d_117[0][0]                 
____________________________________________________________________________________________________
activation_352 (Activation)      (None, None, None, 64 0           batch_normalization_107[0][0]    
____________________________________________________________________________________________________
activation_354 (Activation)      (None, None, None, 64 0           batch_normalization_109[0][0]    
____________________________________________________________________________________________________
activation_357 (Activation)      (None, None, None, 96 0           batch_normalization_112[0][0]    
____________________________________________________________________________________________________
activation_358 (Activation)      (None, None, None, 64 0           batch_normalization_113[0][0]    
____________________________________________________________________________________________________
mixed1 (Concatenate)             (None, None, None, 28 0           activation_352[0][0]             
                                                                   activation_354[0][0]             
                                                                   activation_357[0][0]             
                                                                   activation_358[0][0]             
____________________________________________________________________________________________________
conv2d_121 (Conv2D)              (None, None, None, 64 18432       mixed1[0][0]                     
____________________________________________________________________________________________________
batch_normalization_117 (BatchNo (None, None, None, 64 192         conv2d_121[0][0]                 
____________________________________________________________________________________________________
activation_362 (Activation)      (None, None, None, 64 0           batch_normalization_117[0][0]    
____________________________________________________________________________________________________
conv2d_119 (Conv2D)              (None, None, None, 48 13824       mixed1[0][0]                     
____________________________________________________________________________________________________
conv2d_122 (Conv2D)              (None, None, None, 96 55296       activation_362[0][0]             
____________________________________________________________________________________________________
batch_normalization_115 (BatchNo (None, None, None, 48 144         conv2d_119[0][0]                 
____________________________________________________________________________________________________
batch_normalization_118 (BatchNo (None, None, None, 96 288         conv2d_122[0][0]                 
____________________________________________________________________________________________________
activation_360 (Activation)      (None, None, None, 48 0           batch_normalization_115[0][0]    
____________________________________________________________________________________________________
activation_363 (Activation)      (None, None, None, 96 0           batch_normalization_118[0][0]    
____________________________________________________________________________________________________
average_pooling2d_12 (AveragePoo (None, None, None, 28 0           mixed1[0][0]                     
____________________________________________________________________________________________________
conv2d_118 (Conv2D)              (None, None, None, 64 18432       mixed1[0][0]                     
____________________________________________________________________________________________________
conv2d_120 (Conv2D)              (None, None, None, 64 76800       activation_360[0][0]             
____________________________________________________________________________________________________
conv2d_123 (Conv2D)              (None, None, None, 96 82944       activation_363[0][0]             
____________________________________________________________________________________________________
conv2d_124 (Conv2D)              (None, None, None, 64 18432       average_pooling2d_12[0][0]       
____________________________________________________________________________________________________
batch_normalization_114 (BatchNo (None, None, None, 64 192         conv2d_118[0][0]                 
____________________________________________________________________________________________________
batch_normalization_116 (BatchNo (None, None, None, 64 192         conv2d_120[0][0]                 
____________________________________________________________________________________________________
batch_normalization_119 (BatchNo (None, None, None, 96 288         conv2d_123[0][0]                 
____________________________________________________________________________________________________
batch_normalization_120 (BatchNo (None, None, None, 64 192         conv2d_124[0][0]                 
____________________________________________________________________________________________________
activation_359 (Activation)      (None, None, None, 64 0           batch_normalization_114[0][0]    
____________________________________________________________________________________________________
activation_361 (Activation)      (None, None, None, 64 0           batch_normalization_116[0][0]    
____________________________________________________________________________________________________
activation_364 (Activation)      (None, None, None, 96 0           batch_normalization_119[0][0]    
____________________________________________________________________________________________________
activation_365 (Activation)      (None, None, None, 64 0           batch_normalization_120[0][0]    
____________________________________________________________________________________________________
mixed2 (Concatenate)             (None, None, None, 28 0           activation_359[0][0]             
                                                                   activation_361[0][0]             
                                                                   activation_364[0][0]             
                                                                   activation_365[0][0]             
____________________________________________________________________________________________________
conv2d_126 (Conv2D)              (None, None, None, 64 18432       mixed2[0][0]                     
____________________________________________________________________________________________________
batch_normalization_122 (BatchNo (None, None, None, 64 192         conv2d_126[0][0]                 
____________________________________________________________________________________________________
activation_367 (Activation)      (None, None, None, 64 0           batch_normalization_122[0][0]    
____________________________________________________________________________________________________
conv2d_127 (Conv2D)              (None, None, None, 96 55296       activation_367[0][0]             
____________________________________________________________________________________________________
batch_normalization_123 (BatchNo (None, None, None, 96 288         conv2d_127[0][0]                 
____________________________________________________________________________________________________
activation_368 (Activation)      (None, None, None, 96 0           batch_normalization_123[0][0]    
____________________________________________________________________________________________________
conv2d_125 (Conv2D)              (None, None, None, 38 995328      mixed2[0][0]                     
____________________________________________________________________________________________________
conv2d_128 (Conv2D)              (None, None, None, 96 82944       activation_368[0][0]             
____________________________________________________________________________________________________
batch_normalization_121 (BatchNo (None, None, None, 38 1152        conv2d_125[0][0]                 
____________________________________________________________________________________________________
batch_normalization_124 (BatchNo (None, None, None, 96 288         conv2d_128[0][0]                 
____________________________________________________________________________________________________
activation_366 (Activation)      (None, None, None, 38 0           batch_normalization_121[0][0]    
____________________________________________________________________________________________________
activation_369 (Activation)      (None, None, None, 96 0           batch_normalization_124[0][0]    
____________________________________________________________________________________________________
max_pooling2d_14 (MaxPooling2D)  (None, None, None, 28 0           mixed2[0][0]                     
____________________________________________________________________________________________________
mixed3 (Concatenate)             (None, None, None, 76 0           activation_366[0][0]             
                                                                   activation_369[0][0]             
                                                                   max_pooling2d_14[0][0]           
____________________________________________________________________________________________________
conv2d_133 (Conv2D)              (None, None, None, 12 98304       mixed3[0][0]                     
____________________________________________________________________________________________________
batch_normalization_129 (BatchNo (None, None, None, 12 384         conv2d_133[0][0]                 
____________________________________________________________________________________________________
activation_374 (Activation)      (None, None, None, 12 0           batch_normalization_129[0][0]    
____________________________________________________________________________________________________
conv2d_134 (Conv2D)              (None, None, None, 12 114688      activation_374[0][0]             
____________________________________________________________________________________________________
batch_normalization_130 (BatchNo (None, None, None, 12 384         conv2d_134[0][0]                 
____________________________________________________________________________________________________
activation_375 (Activation)      (None, None, None, 12 0           batch_normalization_130[0][0]    
____________________________________________________________________________________________________
conv2d_130 (Conv2D)              (None, None, None, 12 98304       mixed3[0][0]                     
____________________________________________________________________________________________________
conv2d_135 (Conv2D)              (None, None, None, 12 114688      activation_375[0][0]             
____________________________________________________________________________________________________
batch_normalization_126 (BatchNo (None, None, None, 12 384         conv2d_130[0][0]                 
____________________________________________________________________________________________________
batch_normalization_131 (BatchNo (None, None, None, 12 384         conv2d_135[0][0]                 
____________________________________________________________________________________________________
activation_371 (Activation)      (None, None, None, 12 0           batch_normalization_126[0][0]    
____________________________________________________________________________________________________
activation_376 (Activation)      (None, None, None, 12 0           batch_normalization_131[0][0]    
____________________________________________________________________________________________________
conv2d_131 (Conv2D)              (None, None, None, 12 114688      activation_371[0][0]             
____________________________________________________________________________________________________
conv2d_136 (Conv2D)              (None, None, None, 12 114688      activation_376[0][0]             
____________________________________________________________________________________________________
batch_normalization_127 (BatchNo (None, None, None, 12 384         conv2d_131[0][0]                 
____________________________________________________________________________________________________
batch_normalization_132 (BatchNo (None, None, None, 12 384         conv2d_136[0][0]                 
____________________________________________________________________________________________________
activation_372 (Activation)      (None, None, None, 12 0           batch_normalization_127[0][0]    
____________________________________________________________________________________________________
activation_377 (Activation)      (None, None, None, 12 0           batch_normalization_132[0][0]    
____________________________________________________________________________________________________
average_pooling2d_13 (AveragePoo (None, None, None, 76 0           mixed3[0][0]                     
____________________________________________________________________________________________________
conv2d_129 (Conv2D)              (None, None, None, 19 147456      mixed3[0][0]                     
____________________________________________________________________________________________________
conv2d_132 (Conv2D)              (None, None, None, 19 172032      activation_372[0][0]             
____________________________________________________________________________________________________
conv2d_137 (Conv2D)              (None, None, None, 19 172032      activation_377[0][0]             
____________________________________________________________________________________________________
conv2d_138 (Conv2D)              (None, None, None, 19 147456      average_pooling2d_13[0][0]       
____________________________________________________________________________________________________
batch_normalization_125 (BatchNo (None, None, None, 19 576         conv2d_129[0][0]                 
____________________________________________________________________________________________________
batch_normalization_128 (BatchNo (None, None, None, 19 576         conv2d_132[0][0]                 
____________________________________________________________________________________________________
batch_normalization_133 (BatchNo (None, None, None, 19 576         conv2d_137[0][0]                 
____________________________________________________________________________________________________
batch_normalization_134 (BatchNo (None, None, None, 19 576         conv2d_138[0][0]                 
____________________________________________________________________________________________________
activation_370 (Activation)      (None, None, None, 19 0           batch_normalization_125[0][0]    
____________________________________________________________________________________________________
activation_373 (Activation)      (None, None, None, 19 0           batch_normalization_128[0][0]    
____________________________________________________________________________________________________
activation_378 (Activation)      (None, None, None, 19 0           batch_normalization_133[0][0]    
____________________________________________________________________________________________________
activation_379 (Activation)      (None, None, None, 19 0           batch_normalization_134[0][0]    
____________________________________________________________________________________________________
mixed4 (Concatenate)             (None, None, None, 76 0           activation_370[0][0]             
                                                                   activation_373[0][0]             
                                                                   activation_378[0][0]             
                                                                   activation_379[0][0]             
____________________________________________________________________________________________________
conv2d_143 (Conv2D)              (None, None, None, 16 122880      mixed4[0][0]                     
____________________________________________________________________________________________________
batch_normalization_139 (BatchNo (None, None, None, 16 480         conv2d_143[0][0]                 
____________________________________________________________________________________________________
activation_384 (Activation)      (None, None, None, 16 0           batch_normalization_139[0][0]    
____________________________________________________________________________________________________
conv2d_144 (Conv2D)              (None, None, None, 16 179200      activation_384[0][0]             
____________________________________________________________________________________________________
batch_normalization_140 (BatchNo (None, None, None, 16 480         conv2d_144[0][0]                 
____________________________________________________________________________________________________
activation_385 (Activation)      (None, None, None, 16 0           batch_normalization_140[0][0]    
____________________________________________________________________________________________________
conv2d_140 (Conv2D)              (None, None, None, 16 122880      mixed4[0][0]                     
____________________________________________________________________________________________________
conv2d_145 (Conv2D)              (None, None, None, 16 179200      activation_385[0][0]             
____________________________________________________________________________________________________
batch_normalization_136 (BatchNo (None, None, None, 16 480         conv2d_140[0][0]                 
____________________________________________________________________________________________________
batch_normalization_141 (BatchNo (None, None, None, 16 480         conv2d_145[0][0]                 
____________________________________________________________________________________________________
activation_381 (Activation)      (None, None, None, 16 0           batch_normalization_136[0][0]    
____________________________________________________________________________________________________
activation_386 (Activation)      (None, None, None, 16 0           batch_normalization_141[0][0]    
____________________________________________________________________________________________________
conv2d_141 (Conv2D)              (None, None, None, 16 179200      activation_381[0][0]             
____________________________________________________________________________________________________
conv2d_146 (Conv2D)              (None, None, None, 16 179200      activation_386[0][0]             
____________________________________________________________________________________________________
batch_normalization_137 (BatchNo (None, None, None, 16 480         conv2d_141[0][0]                 
____________________________________________________________________________________________________
batch_normalization_142 (BatchNo (None, None, None, 16 480         conv2d_146[0][0]                 
____________________________________________________________________________________________________
activation_382 (Activation)      (None, None, None, 16 0           batch_normalization_137[0][0]    
____________________________________________________________________________________________________
activation_387 (Activation)      (None, None, None, 16 0           batch_normalization_142[0][0]    
____________________________________________________________________________________________________
average_pooling2d_14 (AveragePoo (None, None, None, 76 0           mixed4[0][0]                     
____________________________________________________________________________________________________
conv2d_139 (Conv2D)              (None, None, None, 19 147456      mixed4[0][0]                     
____________________________________________________________________________________________________
conv2d_142 (Conv2D)              (None, None, None, 19 215040      activation_382[0][0]             
____________________________________________________________________________________________________
conv2d_147 (Conv2D)              (None, None, None, 19 215040      activation_387[0][0]             
____________________________________________________________________________________________________
conv2d_148 (Conv2D)              (None, None, None, 19 147456      average_pooling2d_14[0][0]       
____________________________________________________________________________________________________
batch_normalization_135 (BatchNo (None, None, None, 19 576         conv2d_139[0][0]                 
____________________________________________________________________________________________________
batch_normalization_138 (BatchNo (None, None, None, 19 576         conv2d_142[0][0]                 
____________________________________________________________________________________________________
batch_normalization_143 (BatchNo (None, None, None, 19 576         conv2d_147[0][0]                 
____________________________________________________________________________________________________
batch_normalization_144 (BatchNo (None, None, None, 19 576         conv2d_148[0][0]                 
____________________________________________________________________________________________________
activation_380 (Activation)      (None, None, None, 19 0           batch_normalization_135[0][0]    
____________________________________________________________________________________________________
activation_383 (Activation)      (None, None, None, 19 0           batch_normalization_138[0][0]    
____________________________________________________________________________________________________
activation_388 (Activation)      (None, None, None, 19 0           batch_normalization_143[0][0]    
____________________________________________________________________________________________________
activation_389 (Activation)      (None, None, None, 19 0           batch_normalization_144[0][0]    
____________________________________________________________________________________________________
mixed5 (Concatenate)             (None, None, None, 76 0           activation_380[0][0]             
                                                                   activation_383[0][0]             
                                                                   activation_388[0][0]             
                                                                   activation_389[0][0]             
____________________________________________________________________________________________________
conv2d_153 (Conv2D)              (None, None, None, 16 122880      mixed5[0][0]                     
____________________________________________________________________________________________________
batch_normalization_149 (BatchNo (None, None, None, 16 480         conv2d_153[0][0]                 
____________________________________________________________________________________________________
activation_394 (Activation)      (None, None, None, 16 0           batch_normalization_149[0][0]    
____________________________________________________________________________________________________
conv2d_154 (Conv2D)              (None, None, None, 16 179200      activation_394[0][0]             
____________________________________________________________________________________________________
batch_normalization_150 (BatchNo (None, None, None, 16 480         conv2d_154[0][0]                 
____________________________________________________________________________________________________
activation_395 (Activation)      (None, None, None, 16 0           batch_normalization_150[0][0]    
____________________________________________________________________________________________________
conv2d_150 (Conv2D)              (None, None, None, 16 122880      mixed5[0][0]                     
____________________________________________________________________________________________________
conv2d_155 (Conv2D)              (None, None, None, 16 179200      activation_395[0][0]             
____________________________________________________________________________________________________
batch_normalization_146 (BatchNo (None, None, None, 16 480         conv2d_150[0][0]                 
____________________________________________________________________________________________________
batch_normalization_151 (BatchNo (None, None, None, 16 480         conv2d_155[0][0]                 
____________________________________________________________________________________________________
activation_391 (Activation)      (None, None, None, 16 0           batch_normalization_146[0][0]    
____________________________________________________________________________________________________
activation_396 (Activation)      (None, None, None, 16 0           batch_normalization_151[0][0]    
____________________________________________________________________________________________________
conv2d_151 (Conv2D)              (None, None, None, 16 179200      activation_391[0][0]             
____________________________________________________________________________________________________
conv2d_156 (Conv2D)              (None, None, None, 16 179200      activation_396[0][0]             
____________________________________________________________________________________________________
batch_normalization_147 (BatchNo (None, None, None, 16 480         conv2d_151[0][0]                 
____________________________________________________________________________________________________
batch_normalization_152 (BatchNo (None, None, None, 16 480         conv2d_156[0][0]                 
____________________________________________________________________________________________________
activation_392 (Activation)      (None, None, None, 16 0           batch_normalization_147[0][0]    
____________________________________________________________________________________________________
activation_397 (Activation)      (None, None, None, 16 0           batch_normalization_152[0][0]    
____________________________________________________________________________________________________
average_pooling2d_15 (AveragePoo (None, None, None, 76 0           mixed5[0][0]                     
____________________________________________________________________________________________________
conv2d_149 (Conv2D)              (None, None, None, 19 147456      mixed5[0][0]                     
____________________________________________________________________________________________________
conv2d_152 (Conv2D)              (None, None, None, 19 215040      activation_392[0][0]             
____________________________________________________________________________________________________
conv2d_157 (Conv2D)              (None, None, None, 19 215040      activation_397[0][0]             
____________________________________________________________________________________________________
conv2d_158 (Conv2D)              (None, None, None, 19 147456      average_pooling2d_15[0][0]       
____________________________________________________________________________________________________
batch_normalization_145 (BatchNo (None, None, None, 19 576         conv2d_149[0][0]                 
____________________________________________________________________________________________________
batch_normalization_148 (BatchNo (None, None, None, 19 576         conv2d_152[0][0]                 
____________________________________________________________________________________________________
batch_normalization_153 (BatchNo (None, None, None, 19 576         conv2d_157[0][0]                 
____________________________________________________________________________________________________
batch_normalization_154 (BatchNo (None, None, None, 19 576         conv2d_158[0][0]                 
____________________________________________________________________________________________________
activation_390 (Activation)      (None, None, None, 19 0           batch_normalization_145[0][0]    
____________________________________________________________________________________________________
activation_393 (Activation)      (None, None, None, 19 0           batch_normalization_148[0][0]    
____________________________________________________________________________________________________
activation_398 (Activation)      (None, None, None, 19 0           batch_normalization_153[0][0]    
____________________________________________________________________________________________________
activation_399 (Activation)      (None, None, None, 19 0           batch_normalization_154[0][0]    
____________________________________________________________________________________________________
mixed6 (Concatenate)             (None, None, None, 76 0           activation_390[0][0]             
                                                                   activation_393[0][0]             
                                                                   activation_398[0][0]             
                                                                   activation_399[0][0]             
____________________________________________________________________________________________________
conv2d_163 (Conv2D)              (None, None, None, 19 147456      mixed6[0][0]                     
____________________________________________________________________________________________________
batch_normalization_159 (BatchNo (None, None, None, 19 576         conv2d_163[0][0]                 
____________________________________________________________________________________________________
activation_404 (Activation)      (None, None, None, 19 0           batch_normalization_159[0][0]    
____________________________________________________________________________________________________
conv2d_164 (Conv2D)              (None, None, None, 19 258048      activation_404[0][0]             
____________________________________________________________________________________________________
batch_normalization_160 (BatchNo (None, None, None, 19 576         conv2d_164[0][0]                 
____________________________________________________________________________________________________
activation_405 (Activation)      (None, None, None, 19 0           batch_normalization_160[0][0]    
____________________________________________________________________________________________________
conv2d_160 (Conv2D)              (None, None, None, 19 147456      mixed6[0][0]                     
____________________________________________________________________________________________________
conv2d_165 (Conv2D)              (None, None, None, 19 258048      activation_405[0][0]             
____________________________________________________________________________________________________
batch_normalization_156 (BatchNo (None, None, None, 19 576         conv2d_160[0][0]                 
____________________________________________________________________________________________________
batch_normalization_161 (BatchNo (None, None, None, 19 576         conv2d_165[0][0]                 
____________________________________________________________________________________________________
activation_401 (Activation)      (None, None, None, 19 0           batch_normalization_156[0][0]    
____________________________________________________________________________________________________
activation_406 (Activation)      (None, None, None, 19 0           batch_normalization_161[0][0]    
____________________________________________________________________________________________________
conv2d_161 (Conv2D)              (None, None, None, 19 258048      activation_401[0][0]             
____________________________________________________________________________________________________
conv2d_166 (Conv2D)              (None, None, None, 19 258048      activation_406[0][0]             
____________________________________________________________________________________________________
batch_normalization_157 (BatchNo (None, None, None, 19 576         conv2d_161[0][0]                 
____________________________________________________________________________________________________
batch_normalization_162 (BatchNo (None, None, None, 19 576         conv2d_166[0][0]                 
____________________________________________________________________________________________________
activation_402 (Activation)      (None, None, None, 19 0           batch_normalization_157[0][0]    
____________________________________________________________________________________________________
activation_407 (Activation)      (None, None, None, 19 0           batch_normalization_162[0][0]    
____________________________________________________________________________________________________
average_pooling2d_16 (AveragePoo (None, None, None, 76 0           mixed6[0][0]                     
____________________________________________________________________________________________________
conv2d_159 (Conv2D)              (None, None, None, 19 147456      mixed6[0][0]                     
____________________________________________________________________________________________________
conv2d_162 (Conv2D)              (None, None, None, 19 258048      activation_402[0][0]             
____________________________________________________________________________________________________
conv2d_167 (Conv2D)              (None, None, None, 19 258048      activation_407[0][0]             
____________________________________________________________________________________________________
conv2d_168 (Conv2D)              (None, None, None, 19 147456      average_pooling2d_16[0][0]       
____________________________________________________________________________________________________
batch_normalization_155 (BatchNo (None, None, None, 19 576         conv2d_159[0][0]                 
____________________________________________________________________________________________________
batch_normalization_158 (BatchNo (None, None, None, 19 576         conv2d_162[0][0]                 
____________________________________________________________________________________________________
batch_normalization_163 (BatchNo (None, None, None, 19 576         conv2d_167[0][0]                 
____________________________________________________________________________________________________
batch_normalization_164 (BatchNo (None, None, None, 19 576         conv2d_168[0][0]                 
____________________________________________________________________________________________________
activation_400 (Activation)      (None, None, None, 19 0           batch_normalization_155[0][0]    
____________________________________________________________________________________________________
activation_403 (Activation)      (None, None, None, 19 0           batch_normalization_158[0][0]    
____________________________________________________________________________________________________
activation_408 (Activation)      (None, None, None, 19 0           batch_normalization_163[0][0]    
____________________________________________________________________________________________________
activation_409 (Activation)      (None, None, None, 19 0           batch_normalization_164[0][0]    
____________________________________________________________________________________________________
mixed7 (Concatenate)             (None, None, None, 76 0           activation_400[0][0]             
                                                                   activation_403[0][0]             
                                                                   activation_408[0][0]             
                                                                   activation_409[0][0]             
____________________________________________________________________________________________________
conv2d_171 (Conv2D)              (None, None, None, 19 147456      mixed7[0][0]                     
____________________________________________________________________________________________________
batch_normalization_167 (BatchNo (None, None, None, 19 576         conv2d_171[0][0]                 
____________________________________________________________________________________________________
activation_412 (Activation)      (None, None, None, 19 0           batch_normalization_167[0][0]    
____________________________________________________________________________________________________
conv2d_172 (Conv2D)              (None, None, None, 19 258048      activation_412[0][0]             
____________________________________________________________________________________________________
batch_normalization_168 (BatchNo (None, None, None, 19 576         conv2d_172[0][0]                 
____________________________________________________________________________________________________
activation_413 (Activation)      (None, None, None, 19 0           batch_normalization_168[0][0]    
____________________________________________________________________________________________________
conv2d_169 (Conv2D)              (None, None, None, 19 147456      mixed7[0][0]                     
____________________________________________________________________________________________________
conv2d_173 (Conv2D)              (None, None, None, 19 258048      activation_413[0][0]             
____________________________________________________________________________________________________
batch_normalization_165 (BatchNo (None, None, None, 19 576         conv2d_169[0][0]                 
____________________________________________________________________________________________________
batch_normalization_169 (BatchNo (None, None, None, 19 576         conv2d_173[0][0]                 
____________________________________________________________________________________________________
activation_410 (Activation)      (None, None, None, 19 0           batch_normalization_165[0][0]    
____________________________________________________________________________________________________
activation_414 (Activation)      (None, None, None, 19 0           batch_normalization_169[0][0]    
____________________________________________________________________________________________________
conv2d_170 (Conv2D)              (None, None, None, 32 552960      activation_410[0][0]             
____________________________________________________________________________________________________
conv2d_174 (Conv2D)              (None, None, None, 19 331776      activation_414[0][0]             
____________________________________________________________________________________________________
batch_normalization_166 (BatchNo (None, None, None, 32 960         conv2d_170[0][0]                 
____________________________________________________________________________________________________
batch_normalization_170 (BatchNo (None, None, None, 19 576         conv2d_174[0][0]                 
____________________________________________________________________________________________________
activation_411 (Activation)      (None, None, None, 32 0           batch_normalization_166[0][0]    
____________________________________________________________________________________________________
activation_415 (Activation)      (None, None, None, 19 0           batch_normalization_170[0][0]    
____________________________________________________________________________________________________
max_pooling2d_15 (MaxPooling2D)  (None, None, None, 76 0           mixed7[0][0]                     
____________________________________________________________________________________________________
mixed8 (Concatenate)             (None, None, None, 12 0           activation_411[0][0]             
                                                                   activation_415[0][0]             
                                                                   max_pooling2d_15[0][0]           
____________________________________________________________________________________________________
conv2d_179 (Conv2D)              (None, None, None, 44 573440      mixed8[0][0]                     
____________________________________________________________________________________________________
batch_normalization_175 (BatchNo (None, None, None, 44 1344        conv2d_179[0][0]                 
____________________________________________________________________________________________________
activation_420 (Activation)      (None, None, None, 44 0           batch_normalization_175[0][0]    
____________________________________________________________________________________________________
conv2d_176 (Conv2D)              (None, None, None, 38 491520      mixed8[0][0]                     
____________________________________________________________________________________________________
conv2d_180 (Conv2D)              (None, None, None, 38 1548288     activation_420[0][0]             
____________________________________________________________________________________________________
batch_normalization_172 (BatchNo (None, None, None, 38 1152        conv2d_176[0][0]                 
____________________________________________________________________________________________________
batch_normalization_176 (BatchNo (None, None, None, 38 1152        conv2d_180[0][0]                 
____________________________________________________________________________________________________
activation_417 (Activation)      (None, None, None, 38 0           batch_normalization_172[0][0]    
____________________________________________________________________________________________________
activation_421 (Activation)      (None, None, None, 38 0           batch_normalization_176[0][0]    
____________________________________________________________________________________________________
conv2d_177 (Conv2D)              (None, None, None, 38 442368      activation_417[0][0]             
____________________________________________________________________________________________________
conv2d_178 (Conv2D)              (None, None, None, 38 442368      activation_417[0][0]             
____________________________________________________________________________________________________
conv2d_181 (Conv2D)              (None, None, None, 38 442368      activation_421[0][0]             
____________________________________________________________________________________________________
conv2d_182 (Conv2D)              (None, None, None, 38 442368      activation_421[0][0]             
____________________________________________________________________________________________________
average_pooling2d_17 (AveragePoo (None, None, None, 12 0           mixed8[0][0]                     
____________________________________________________________________________________________________
conv2d_175 (Conv2D)              (None, None, None, 32 409600      mixed8[0][0]                     
____________________________________________________________________________________________________
batch_normalization_173 (BatchNo (None, None, None, 38 1152        conv2d_177[0][0]                 
____________________________________________________________________________________________________
batch_normalization_174 (BatchNo (None, None, None, 38 1152        conv2d_178[0][0]                 
____________________________________________________________________________________________________
batch_normalization_177 (BatchNo (None, None, None, 38 1152        conv2d_181[0][0]                 
____________________________________________________________________________________________________
batch_normalization_178 (BatchNo (None, None, None, 38 1152        conv2d_182[0][0]                 
____________________________________________________________________________________________________
conv2d_183 (Conv2D)              (None, None, None, 19 245760      average_pooling2d_17[0][0]       
____________________________________________________________________________________________________
batch_normalization_171 (BatchNo (None, None, None, 32 960         conv2d_175[0][0]                 
____________________________________________________________________________________________________
activation_418 (Activation)      (None, None, None, 38 0           batch_normalization_173[0][0]    
____________________________________________________________________________________________________
activation_419 (Activation)      (None, None, None, 38 0           batch_normalization_174[0][0]    
____________________________________________________________________________________________________
activation_422 (Activation)      (None, None, None, 38 0           batch_normalization_177[0][0]    
____________________________________________________________________________________________________
activation_423 (Activation)      (None, None, None, 38 0           batch_normalization_178[0][0]    
____________________________________________________________________________________________________
batch_normalization_179 (BatchNo (None, None, None, 19 576         conv2d_183[0][0]                 
____________________________________________________________________________________________________
activation_416 (Activation)      (None, None, None, 32 0           batch_normalization_171[0][0]    
____________________________________________________________________________________________________
mixed9_0 (Concatenate)           (None, None, None, 76 0           activation_418[0][0]             
                                                                   activation_419[0][0]             
____________________________________________________________________________________________________
concatenate_3 (Concatenate)      (None, None, None, 76 0           activation_422[0][0]             
                                                                   activation_423[0][0]             
____________________________________________________________________________________________________
activation_424 (Activation)      (None, None, None, 19 0           batch_normalization_179[0][0]    
____________________________________________________________________________________________________
mixed9 (Concatenate)             (None, None, None, 20 0           activation_416[0][0]             
                                                                   mixed9_0[0][0]                   
                                                                   concatenate_3[0][0]              
                                                                   activation_424[0][0]             
____________________________________________________________________________________________________
conv2d_188 (Conv2D)              (None, None, None, 44 917504      mixed9[0][0]                     
____________________________________________________________________________________________________
batch_normalization_184 (BatchNo (None, None, None, 44 1344        conv2d_188[0][0]                 
____________________________________________________________________________________________________
activation_429 (Activation)      (None, None, None, 44 0           batch_normalization_184[0][0]    
____________________________________________________________________________________________________
conv2d_185 (Conv2D)              (None, None, None, 38 786432      mixed9[0][0]                     
____________________________________________________________________________________________________
conv2d_189 (Conv2D)              (None, None, None, 38 1548288     activation_429[0][0]             
____________________________________________________________________________________________________
batch_normalization_181 (BatchNo (None, None, None, 38 1152        conv2d_185[0][0]                 
____________________________________________________________________________________________________
batch_normalization_185 (BatchNo (None, None, None, 38 1152        conv2d_189[0][0]                 
____________________________________________________________________________________________________
activation_426 (Activation)      (None, None, None, 38 0           batch_normalization_181[0][0]    
____________________________________________________________________________________________________
activation_430 (Activation)      (None, None, None, 38 0           batch_normalization_185[0][0]    
____________________________________________________________________________________________________
conv2d_186 (Conv2D)              (None, None, None, 38 442368      activation_426[0][0]             
____________________________________________________________________________________________________
conv2d_187 (Conv2D)              (None, None, None, 38 442368      activation_426[0][0]             
____________________________________________________________________________________________________
conv2d_190 (Conv2D)              (None, None, None, 38 442368      activation_430[0][0]             
____________________________________________________________________________________________________
conv2d_191 (Conv2D)              (None, None, None, 38 442368      activation_430[0][0]             
____________________________________________________________________________________________________
average_pooling2d_18 (AveragePoo (None, None, None, 20 0           mixed9[0][0]                     
____________________________________________________________________________________________________
conv2d_184 (Conv2D)              (None, None, None, 32 655360      mixed9[0][0]                     
____________________________________________________________________________________________________
batch_normalization_182 (BatchNo (None, None, None, 38 1152        conv2d_186[0][0]                 
____________________________________________________________________________________________________
batch_normalization_183 (BatchNo (None, None, None, 38 1152        conv2d_187[0][0]                 
____________________________________________________________________________________________________
batch_normalization_186 (BatchNo (None, None, None, 38 1152        conv2d_190[0][0]                 
____________________________________________________________________________________________________
batch_normalization_187 (BatchNo (None, None, None, 38 1152        conv2d_191[0][0]                 
____________________________________________________________________________________________________
conv2d_192 (Conv2D)              (None, None, None, 19 393216      average_pooling2d_18[0][0]       
____________________________________________________________________________________________________
batch_normalization_180 (BatchNo (None, None, None, 32 960         conv2d_184[0][0]                 
____________________________________________________________________________________________________
activation_427 (Activation)      (None, None, None, 38 0           batch_normalization_182[0][0]    
____________________________________________________________________________________________________
activation_428 (Activation)      (None, None, None, 38 0           batch_normalization_183[0][0]    
____________________________________________________________________________________________________
activation_431 (Activation)      (None, None, None, 38 0           batch_normalization_186[0][0]    
____________________________________________________________________________________________________
activation_432 (Activation)      (None, None, None, 38 0           batch_normalization_187[0][0]    
____________________________________________________________________________________________________
batch_normalization_188 (BatchNo (None, None, None, 19 576         conv2d_192[0][0]                 
____________________________________________________________________________________________________
activation_425 (Activation)      (None, None, None, 32 0           batch_normalization_180[0][0]    
____________________________________________________________________________________________________
mixed9_1 (Concatenate)           (None, None, None, 76 0           activation_427[0][0]             
                                                                   activation_428[0][0]             
____________________________________________________________________________________________________
concatenate_4 (Concatenate)      (None, None, None, 76 0           activation_431[0][0]             
                                                                   activation_432[0][0]             
____________________________________________________________________________________________________
activation_433 (Activation)      (None, None, None, 19 0           batch_normalization_188[0][0]    
____________________________________________________________________________________________________
mixed10 (Concatenate)            (None, None, None, 20 0           activation_425[0][0]             
                                                                   mixed9_1[0][0]                   
                                                                   concatenate_4[0][0]              
                                                                   activation_433[0][0]             
____________________________________________________________________________________________________
global_average_pooling2d_7 (Glob (None, 2048)          0           mixed10[0][0]                    
____________________________________________________________________________________________________
dense_11 (Dense)                 (None, 133)           272517      global_average_pooling2d_7[0][0] 
====================================================================================================
Total params: 22,075,301
Trainable params: 16,488,453
Non-trainable params: 5,586,848
____________________________________________________________________________________________________
In [51]:
steps = math.ceil(train_tensors.shape[0]/batch_size)
validation_steps = math.ceil(valid_tensors.shape[0]/batch_size)
print('Training Samples: {} Validation Samples: {} Batch Size: {} Steps: {}'.format(
      train_tensors.shape[0], valid_tensors.shape[0], batch_size, steps))

epochs = 20
epochtimer = EpochTimer()

hist = finetune_model.fit_generator(
    train_generator,
    validation_data=validation_generator,
    epochs=epochs,
    steps_per_epoch=steps,
    validation_steps=validation_steps,
    callbacks=[epochtimer])

show_history_graph(hist)

finetune_model_file = 'saved_models/weights.best.{}.hdf5'.format('inceptionv3_finetune')
finetune_model.save(finetune_model_file)
Training Samples: 6680 Validation Samples: 835 Batch Size: 100 Steps: 67
Epoch 1/20
66/67 [============================>.] - ETA: 2s - loss: 0.2659 - acc: 0.9253Epoch 0 took 179.31397139799992 seconds
67/67 [==============================] - 179s - loss: 0.2662 - acc: 0.9252 - val_loss: 0.6292 - val_acc: 0.8084
Epoch 2/20
66/67 [============================>.] - ETA: 2s - loss: 0.2443 - acc: 0.9311Epoch 1 took 171.3379542470011 seconds
67/67 [==============================] - 171s - loss: 0.2438 - acc: 0.9314 - val_loss: 0.5883 - val_acc: 0.8180
Epoch 3/20
66/67 [============================>.] - ETA: 2s - loss: 0.2426 - acc: 0.9314Epoch 2 took 170.2248470020004 seconds
67/67 [==============================] - 170s - loss: 0.2424 - acc: 0.9312 - val_loss: 0.5372 - val_acc: 0.8395
Epoch 4/20
66/67 [============================>.] - ETA: 2s - loss: 0.2210 - acc: 0.9377Epoch 3 took 169.95418436799991 seconds
67/67 [==============================] - 169s - loss: 0.2202 - acc: 0.9379 - val_loss: 0.5165 - val_acc: 0.8407
Epoch 5/20
66/67 [============================>.] - ETA: 2s - loss: 0.2124 - acc: 0.9421Epoch 4 took 169.9291799980001 seconds
67/67 [==============================] - 169s - loss: 0.2125 - acc: 0.9421 - val_loss: 0.5706 - val_acc: 0.8383
Epoch 6/20
66/67 [============================>.] - ETA: 2s - loss: 0.2090 - acc: 0.9428Epoch 5 took 169.5245090290009 seconds
67/67 [==============================] - 169s - loss: 0.2076 - acc: 0.9435 - val_loss: 0.5200 - val_acc: 0.8407
Epoch 7/20
66/67 [============================>.] - ETA: 2s - loss: 0.1990 - acc: 0.9456Epoch 6 took 170.1810389149996 seconds
67/67 [==============================] - 170s - loss: 0.1982 - acc: 0.9461 - val_loss: 0.5529 - val_acc: 0.8204
Epoch 8/20
66/67 [============================>.] - ETA: 2s - loss: 0.1936 - acc: 0.9475Epoch 7 took 169.80094934799854 seconds
67/67 [==============================] - 169s - loss: 0.1948 - acc: 0.9471 - val_loss: 0.5309 - val_acc: 0.8455
Epoch 9/20
66/67 [============================>.] - ETA: 2s - loss: 0.1808 - acc: 0.9501Epoch 8 took 170.19115949200022 seconds
67/67 [==============================] - 170s - loss: 0.1810 - acc: 0.9497 - val_loss: 0.5383 - val_acc: 0.8431
Epoch 10/20
66/67 [============================>.] - ETA: 2s - loss: 0.1845 - acc: 0.9507Epoch 9 took 170.51170235899917 seconds
67/67 [==============================] - 170s - loss: 0.1849 - acc: 0.9504 - val_loss: 0.5334 - val_acc: 0.8275
Epoch 11/20
66/67 [============================>.] - ETA: 2s - loss: 0.1815 - acc: 0.9512Epoch 10 took 169.88859605699872 seconds
67/67 [==============================] - 169s - loss: 0.1809 - acc: 0.9513 - val_loss: 0.4893 - val_acc: 0.8599
Epoch 12/20
66/67 [============================>.] - ETA: 2s - loss: 0.1821 - acc: 0.9485Epoch 11 took 169.91181294800117 seconds
67/67 [==============================] - 169s - loss: 0.1816 - acc: 0.9490 - val_loss: 0.5562 - val_acc: 0.8335
Epoch 13/20
66/67 [============================>.] - ETA: 2s - loss: 0.1687 - acc: 0.9577Epoch 12 took 170.44122359599896 seconds
67/67 [==============================] - 170s - loss: 0.1686 - acc: 0.9578 - val_loss: 0.5517 - val_acc: 0.8479
Epoch 14/20
66/67 [============================>.] - ETA: 2s - loss: 0.1709 - acc: 0.9525Epoch 13 took 170.01451160800025 seconds
67/67 [==============================] - 170s - loss: 0.1705 - acc: 0.9526 - val_loss: 0.5312 - val_acc: 0.8216
Epoch 15/20
66/67 [============================>.] - ETA: 2s - loss: 0.1751 - acc: 0.9528Epoch 14 took 169.87305544099945 seconds
67/67 [==============================] - 169s - loss: 0.1754 - acc: 0.9527 - val_loss: 0.4682 - val_acc: 0.8575
Epoch 16/20
66/67 [============================>.] - ETA: 2s - loss: 0.1620 - acc: 0.9563Epoch 15 took 169.92311470700042 seconds
67/67 [==============================] - 169s - loss: 0.1622 - acc: 0.9562 - val_loss: 0.4674 - val_acc: 0.8479
Epoch 17/20
66/67 [============================>.] - ETA: 2s - loss: 0.1583 - acc: 0.9584Epoch 16 took 169.75574349499948 seconds
67/67 [==============================] - 169s - loss: 0.1579 - acc: 0.9588 - val_loss: 0.5071 - val_acc: 0.8491
Epoch 18/20
66/67 [============================>.] - ETA: 2s - loss: 0.1566 - acc: 0.9605Epoch 17 took 170.673147771 seconds
67/67 [==============================] - 170s - loss: 0.1563 - acc: 0.9608 - val_loss: 0.5022 - val_acc: 0.8563
Epoch 19/20
66/67 [============================>.] - ETA: 2s - loss: 0.1548 - acc: 0.9603Epoch 18 took 170.28154546599944 seconds
67/67 [==============================] - 170s - loss: 0.1558 - acc: 0.9600 - val_loss: 0.4756 - val_acc: 0.8551
Epoch 20/20
66/67 [============================>.] - ETA: 2s - loss: 0.1555 - acc: 0.9603Epoch 19 took 170.75071191400093 seconds
67/67 [==============================] - 170s - loss: 0.1550 - acc: 0.9605 - val_loss: 0.5039 - val_acc: 0.8455
Training took 3412.5265999000003 seconds
In [52]:
predictions = [np.argmax(finetune_model.predict(np.expand_dims(feature, axis=0))) for feature in inception_test_tensors]

# report test accuracy
test_accuracy = 100*np.sum(np.array(predictions)==np.argmax(test_targets, axis=1))/len(predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 87.7990%
In [54]:
finetune_model_file = 'saved_models/weights.best.{}.hdf5'.format('inceptionv3_finetune')
finetune_model.load_weights(finetune_model_file)

from keras.applications.inception_v3 import InceptionV3
from keras.applications.inception_v3 import preprocess_input as preprocess_inception_input

def extract_InceptionV3(tensor):
    return InceptionV3(weights='imagenet', include_top=False).predict(preprocess_inception_input(tensor))

### Function that takes a path to an image as input
### and returns the dog breed that is predicted by the finetuned model.
def breed_detector(img_path, selected_model, bottleneck=True, img_width=223, img_height=223):
    tensor = path_to_tensor(img_path, img_width, img_height)
    if bottleneck:
        tensor = extract_InceptionV3(tensor)
    else:
        tensor = preprocess_inception_input(tensor)

    predictions = selected_model.predict(tensor)
    y_hat = np.argmax(predictions)
    return dog_names[y_hat]

Results

With data augmentation and only training the top layers: Test accuracy: 85.8852%

After finetuning for 20 epochs with a very small learning rate and SGD optimizer the test accuracy went up to: 87.7990%. Based on the figures it is quite possible to achieve an even better learning rate with much longer training times.

It was really helpful and I learned a lot for potential future problems doing this additional exercise and would recommend to include it or at least some tutorial on how to do this.

In [49]:
# History graphs for the training of the top layers:
show_history_graph(hist)
In [53]:
# History graphs for the fine tuning of the 
# NB_IV3_LAYERS which correspond to the top 2 inception blocks in the inceptionv3 architecture
show_history_graph(hist)
In [ ]: